# Create your views here.
# Create your views here.
from models import *
from django.contrib.sessions.backends.db import SessionStore
from django.shortcuts import render_to_response
from django.shortcuts import HttpResponse
from django.shortcuts import HttpResponseRedirect
from django.template import RequestContext
import operator
import datetime
from datetime import date
import time
#import oembed
from forms import *
from Eventati.App.forms import EditEventForm
from django.core.mail import send_mail
#oembed.autodiscover()
#import twilio.twiml
from Eventati.settings import MEDIA_ROOT
from django.utils import simplejson    
from django import forms
from forms import UploadPhoto
from Eventati.App.models import Photo
from forms import UploadVideo

from django.template.context import Context

emailSession = SessionStore()


def createLocation(request):                    
   if request.method=="POST" :
       eventID = request.session['eventid']
       event = Event.objects.get(pk = eventID)
       bno = request.POST.get('bno', '')
       st = request.POST.get('st', '')
       city = request.POST.get('city', '')
       country = request.POST.get('country', '')
       new_location=Locations.objects.create( BlockNumber=bno,Street=st,city=city, Country=country, event = event)
       new_location.save()
       return viewPayment(request)
   return render_to_response ('CLocation.html', locals(),context_instance=RequestContext(request)) 

#'''
#def createLocation(request):
#    
#    Args:request
#        
#    Returns:In the first call it will return the Clocation template and after submitting the form the listlocations template will be rendered
#        
#    how to use the function:open the url "localhost:8000/location/create"
#        
#'''	
#def createLocation(request):                    
#   if request.method=="POST" :
#       bno = request.POST.get('bno', '')
#       st = request.POST.get('st', '')
#       city = request.POST.get('city', '')
#       country = request.POST.get('country', '')
#       new_location=Location.objects.create( BlockNumber=bno,Street=st,city=city, Country=country)
#       new_location.save()
#       return render_to_response("listlocations.html", {'loc': new_location})
#   return render_to_response ('CLocation.html', locals(),context_instance=RequestContext(request)) 

#'''
#def ListLocation(request):
#    
#    Args:
#        
#    Returns: 
#        
#    how to use the function:
#        
#'''	
#def listLocations(request):
    #Locations=Location.objects.all()
    #return render_to_response ('listlocations.html', locals(),context_instance=RequestContext(request)) 


def homePage(request):
    """
    Author: Amina Kadry
    
    Story: C1-4
    
        The method transfers to the home page
        
    Args:
        The method takes no arguments
        
    Returns:
        The method transfers to the home page
        
    How the method functions:
        http://localhost:8000/homePage

    """
    
    variables = User.objects.all()
    return render_to_response("Signup.html", variables,RequestContext(request))
    

def logIn(request):
    """
	Author: Pauline George

	Story : C1-2
		
		the method allows the user to login to the website by entering both email and password.
	Args:
		The method takes no arguments, it uses method "Post" to 
		
	Returns:	
	   the method redirects the user to the dash board page if he is successfully logged in if not the page refresh with a message of what went wrong 
    Exception:
       if the user tried t login with out having an account a message "Your email does not exist" appears
	   if the user entered a wrong password a message "Your password didnt match" appears
	   if the user forgot to active the acoun before loging in "Your account is not active yet. Please activate it" appears 

	"""
    flag = "False"
    users = User.objects.all()
    if request.method=="POST":
        userEmail = request.POST['email']
        for user in users:
            if user.email==userEmail:
                flag= "True"
                break
        if flag=="True":       
                user = User.objects.get(email = userEmail)
                if user.Active:
                    if user.password == request.POST['password'] :
                        emailSession['email'] =  request.POST['email']
                        request.session['email'] = request.POST['email']
                        emailSession.save()
                        emailSession.set_expiry(0)
                        emailSession.save()
                   
                       
                        return showDashboard(request)
                    else:
                        match = "Your password didnt match"
                        return render_to_response("Signup.html", locals())
                else:
                    notActive = "Your account is not active yet. Please activate it"
                    return render_to_response("Signup.html", locals())
        else:
            notFound = "Your email does not exist"
            return render_to_response("Signup.html", locals())
    #else:
                #return HttpResponse("Your email and password didnt match")
    
    
def change(request):
    return render_to_response("PasswordReset.html", locals())
            
def resetPassword(request):
    """
	Author: Pauline George

	Story : C1-3
		
		the method allows the user to reset his password by entering his email , old password and the new one
	Args:
		The method takes no arguments
		
	Returns:	
	   the method redirects the user to the home page to allow the user to login after reseting the password , 
	   if the user was not found the method redirects him to signup first 


	"""
    flag="False"
    
    userEmail = request.POST['email']
    for user in User.objects.all():
        if user.email==userEmail:
            flag="True"
            print "EMAIL FOUND"
            break
    if flag=="True":
        user = User.objects.get(email=userEmail)
    
        if user.password == request.POST['oldpassword']:
                newPassword = request.POST['newpassword']
                confirmpasswordHtml = request.POST['confirmpassword']
                if newPassword!=confirmpasswordHtml:
                    confirmPasswordFailed = "Confirm password failed"
                    return render_to_response("PasswordReset.html", locals())
                
                user.password = newPassword
                user.confirmpassword = confirmpasswordHtml
                user.save()
                success="You have successfully changed your password"
                return render_to_response("Signup.html", locals())
        else:
                resetMatch="Your old password is incorrect"
                return render_to_response("PasswordReset.html", locals())  
    else:
        print "DOES NOT EXIST"
        resetNotFound = "Your email does not exist."
        return render_to_response("PasswordReset.html", locals())

            

        


def signup(request):
    """
    Author: Amina Kadry
    
    Story: C1-1
        
        The method creates a new account for the user, he provides his information including first name
        last name, email, password, password confirmation and phone number. it validates the password entered
        and checks that the email has not been used before then sends him an email with activation code
        to activate his account
    Args: 
        There are no attributes given for the method itself
        However this method is initiated through "POST" which takes from the user:
        first_name(text): firstName
        last_name(text): lastName
        email(text): email
        password(password): password
        confirmpassword(password): confirmPassword
        phoneNum(text): phoneNumber
    
        
    Returns: 
        The method redirects to the activation page to enter the activation code
    
    How to use the function:
        http://localhost:8000/signup
    Exception:
        It refreshes the page and displays the following:
        if the user entered a wrong email format, "Please enter a valid email" 
        if the user entered an existing email, "Email already exists" 
        if the password doesn't meet requirements, "Password length can't be less than 5 characters and doesn't exceed 10"
        if the confirm password isn't equal to the password, "Confirm password failed"
        if the users enters phone number in wrong format, "Please enter a valid phone number"
        if the user doesn't enter all the fields, "Please enter all fields"  
	"""

    
    if request.method == "POST" :
        users = User.objects.all()
        firstName = request.POST.get('first_name')
        lastName = request.POST.get('last_name')
        getEmail = request.POST.get('email')
        password = request.POST.get('password')
        confirmPassword = request.POST.get('confirm_password')
        phoneNumber = request.POST.get('phone') 
        for user in users: 
            if user.email == getEmail:
                print "EMAIL EXISTS"
                emailExists = "Email already exists. Please enter another email"
                return render_to_response("Signup.html", locals())
       
        newUser = User.objects.create(first_name=firstName, last_name=lastName, email=getEmail, password=password, confirmpassword=confirmPassword, phone=phoneNumber)
        newUser.save()
        getNumber = newUser.id
        print getNumber
        stringNum = str(getNumber)
        send_mail('Notification', 'Dear ' + firstName+ " " + lastName + '\n Your account has been created. \n Welcome to Eventati. \n Please click on the link below to activate your account and enter this code: ' + stringNum + '\n http://localhost:8000/activateAccount/ \nEventati Team',
                         'eventati.noreply@gmail.com', [getEmail], False, 'eventati.noreply', 'Eventati2012')
        return render_to_response("Activation.html", locals())
       
        
    else:
        return render_to_response("Signup.html", RequestContext(request))
    
def validateEmail(email):
    """
    Author: Amina Kadry
    
    Story: C1-1
    
        The method checks the validation of the email address entered by the user
    Args:
        The method takes the email as an attribute
    Returns:
        The method returns true if the email is valid and returns false if the email is invalid
        
    """
    from django.core.validators import validate_email
    from django.core.exceptions import ValidationError
    try:
        validate_email(email)
        return True
    except ValidationError:
        return False
    
def representsInt(s):
    """
    Author: Amina Kadry
    
    Story: C1-1
    
        The method checks the validation of the phone number entered by the user
    Args:
        The method takes the phone number as an attribute
        
    Returns:
        The method returns true if the phone number entered could be parsed as an int and returns false if it could not be parsed as an int
        
    """
    try: 
        int(s)
        return True
    except ValueError:
        return False

def activateAccount(request):
    """
    Author: Amina Kadry
    
    Story: C1-1
    
        This method transfers to the activation page
    Args:
        This methods takes no arguments
    Returns:
        This methods redirects to the activation page
    How to use the function:
        http://localhost:8000/activateAccount
    """ 
    return render_to_response("Activation.html", locals())
   
def activate(request):
    """
    Author: Amina Kadry
    
    Story: C1-1
    
        This method activates the account for the user. The user enters his email, password, and his activation code(sent by email after signing up)
    
    Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST" which takes from the user:
        email(text): email
        password(password): password
        
    Returns: 
        This methods sends an email to the user notifying him that his account has been activated redirects to the login page if successful
    
    How to use the function:
        http://localhost:8000/activate
        
    Exception:
        It refreshes the page and displays the following:
        If the user entered a non-existing email, "Your email does not exist. Please enter a correct email"
        If the user entered a wrong password, "Your password is incorrect. Please enter your correct password"
        If the user entered a wrong activation code, "Your code is incorrect. Please enter your correct code"
        If the user has already activated his account, "Your account is already active."


   """
   
        
    flag = False
    getActivationEmail = request.POST.get('activationEmail')
    print getActivationEmail
    for user in User.objects.all():
        if user.email==getActivationEmail:
            flag= "True"
            break
    if flag=="True":  
        if User.objects.get(email=getActivationEmail).Active!=True:
            getActivationPassword = request.POST.get('activationPassword')
            getActivationCode = request.POST.get('number')
            if representsInt(getActivationCode):
                        
                intActivationCode = int(getActivationCode)
                print getActivationCode
            else:
                activationIntFailed = "Please enter a valid activation code"
                return render_to_response("Activation.html", locals())
                  
                     
            password= User.objects.get(email=getActivationEmail).password
            if (getActivationPassword!=password):
                activationPassFailed = "Your password is incorrect. Please enter your correct password"
                return render_to_response("Activation.html", locals())
            if (intActivationCode!=User.objects.get(email=getActivationEmail).id):
                activationCodeFailed = "Your code is incorrect. Please enter your correct code"
                return render_to_response("Activation.html", locals())
            user = User.objects.get(email=getActivationEmail)
            user.Active = True
            user.save()
            send_mail('Notification', 'Dear ' + user.first_name +" " +  user.last_name + '\n Your account has been activated.  \n Your password is: ' + getActivationPassword + '\nTo login to your account, please click on the link below: \n http://localhost:8000/homePage/ \n Thank you. \nEventati Team',
                              'eventati.noreply@gmail.com', [getActivationEmail], False, 'eventati.noreply', 'Eventati2012')
            print user.Active
            return render_to_response("Signup.html", locals())
        else:
            activeAccount= "Your account is already active."
            return render_to_response("Activation.html", locals())

    else:
        activationEmailFailed = "Your email does not exist. Please enter a correct email"
        return render_to_response("Activation.html", locals())
    
    
        

def logout(request):
    """
    Author: Amina Kadry
    
    Story: C1-13
    
        This method deletes the session, logs the user out and redirects to the login page
    Args:
        This method takes no arguments
     
    Returns:
        This method transfers to the login page
        
    How to use the function:
        http://localhost:8000/logout
        
    Exception:
        if the user is not logged in a message "You aren't logged in" is displayed
    """
    try:
        if emailSession['email']== "":
            logout = "Please login in"
            return render_to_response("Signup.html", locals())
        else:
            
        
            userEmailSession= emailSession['email']
            userRequestSession = request.session['email']
            print "SESSION " + userEmailSession
            print "REQUEST " + userRequestSession
            try: 
                emailSession['email'] = ""
                request.session['email'] = ""
                loggedOut = "You're logged out."
                
            except KeyError:
                pass
            return render_to_response("Signup.html", locals())
    except:
        logout = "Please login in"
        return render_to_response("Signup.html", locals())
    
def addChannel(request):
    """
	addChannel Documentation 
		Author: Hana Saoud
		Story: C4-11
		This method reads the link entered by the user and verifies that it is in the correct format
		and created a new LiveStream object.
		Args: The method takes no inputs and take a request from the live stream HTML
		Returns:
		the method redirects to the LiveStream html (same page) if the link is incorrect and returns and error message
		and if  the link is correct the method rediects to success.html
		How it works:
		When the event creator clicks on the Submit button on livestream.html this method is called
	"""
    if request.method == "POST":
        link = request.POST.get('channel', '')
        correctUrl1 = "http://www.ustream.tv/channel"
        correctUrl2 = "www.ustream.tv/channel"
           
        if link[0:29] == correctUrl1:
            isCorrect= True
            channelID = link[29:]
            resource = "http://www.ustream.tv/embed" + channelID
            newLivestream = LiveStream.objects.create(channel=resource)
            newLivestream.save()
            request.session['livestream'] = newLivestream
            return viewSuccess(request)
        elif link[0:22] == correctUrl2:
            isCorrect= True
            channelID = link[22:]
            resource = "http://www.ustream.tv/embed" + channelID
            newLivestream = LiveStream.objects.create(channel=resource)
            newLivestream.save()
            request.session['livestream'] = newLivestream
            return viewSuccess(request)
        
        elif len(link) == 0:
            errorMsg = "You didn't enter a link. Please enter your channel's link."
            return render_to_response("LiveStream.html", {'errorMsg': errorMsg})
        else:
            errorMsg = "The link entered is incorrect. Please enter the correct link."
            return render_to_response("LiveStream.html", {'errorMsg': errorMsg})
    else:
        return render_to_response("LiveStream.html", RequestContext(request))  

      
def viewChannel(request):
	"""
	viewChannel Documentation 
	Author: Hana Saoud
	Story: C4-11
	This method is used to redirect to a page with the livestream channel embedded
	Args: The method takes no inputs and take a request from e
	Returns:
	the method returns ViewLiveStream.html which has the channel embedded
	How it works:
	by clicking hyperlink channel in the livestream component
	"""
	eventId = request.session['eventid']
	event = Event.objects.get(id = eventId)
	channel = event.template.liveStream.channel
	return render_to_response('ViewLiveStream.html', locals())
    
def editLiveStream(request):
    """
    Author: Ola Magdy
    Story: C2-7
    def editLiveStream(request):
    The method edits the new live stream channel of the event from the event page after the event was launched
    Args
    This method takes no attributes however it uses the POST method to retrieve the new channel
    Returns
    There is no output however it returns the user back to the event page with the edited livestream through render.response
    """
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk = currentEventId)
    template=currentEvent.template
    currentComponents= SelectedComponents.objects.filter(template=template)
    print currentComponents
    for c in currentComponents:
        if c.name =="Live Stream":
            if request.method == "POST":
                link = request.POST.get('channel', '')
                
                if link[0:29] == "http://www.ustream.tv/channel":
                    channelID = link[29:]
                    resource = "http://www.ustream.tv/embed" + channelID
                    template.liveStream.channel = resource
                    currentEvent.template = template
                    template.liveStream.save()
                    template.save()
                    currentEvent.save()
                    return viewEvent(request, currentEventId)
                else:
                    errormsg = "The link entered is incorrect. Please enter the correct link."
                    return render_to_response("EditLiveStream.html", {'errormsg': errormsg})
            else:
                return render_to_response("EditLiveStream.html", RequestContext(request))
      
def sendInvitation(request):
    """
    Author: Amina Kadry
    
    Story: C1-12
    
        This method redirects to an html page where the creator of the event can invite people to this event
    Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST"
        
    Returns:
        Redirects to html page where there is a list of all users that creator can invite
        
    how the function works
        Redirects to the page where the creator can invite people to the event
        http://localhost:8000/sendInvitation
    Exception:
        if the user is not logged in a message "Please log in" will be displayed
  """
    try:
        if emailSession['email']== "":
            logout = "Please login in"
            return render_to_response("Signup.html", locals())
        else:
             users = User.objects.all()
             return render_to_response("Invite.html", locals())   
            
    except:
          logout = "Please login in"
          return render_to_response("Signup.html", locals())                                
        
   
 
        
        
def joinEvent(request):
    """
    Author: Amina Kadry
    
    Story: C1-4
    
        this method adds the user into the attending list of the event only if it is a private event and he is
        invited or if it is a public event 
    Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST"
    Return:
        It refreshes the page after adding the user in the attending list
    How the function works:
        the method is called upon clicking on the attending button which is viewed in the event page
        http://localhost:8000/joinEvent/
    Exception:
        If the user is not logged in, he will be redirected to the homepage with a message displayed :"Please login"
        If the user clicks attending and he is already attending, the page will be refreshed
        If the event is private and the user click on attending without being invited, the page will be refreshed
    
   """
    try:
        #if request.session['email']==""
        if request.session['email']== "":
            logout = "Please login in"
            return render_to_response("Signup.html", locals())
        else:
            
                attending = Attending.objects.all()
                maybeAttending = MaybeAttending.objects.all()
                notAttending = NotAttending.objects.all()
                eventID = request.session['eventid']
                getEvent = Event.objects.get(pk=eventID)
                userEmail = request.session['email']
                events = Event.objects.all()
                users = User.objects.all()
                invited = Invited.objects.all()
                getUser = User.objects.get(email=userEmail)
                if getEvent.isPublic != True:
                    for invitedUser in invited:
                        if invitedUser.user.email == userEmail and invitedUser.event == getEvent:
                            for attendingUser in attending:
                                if attendingUser.user.email==userEmail and attendingUser.event == getEvent:
                                    attended = "Already responded"
                                    return viewEvent(request, eventID)
                            for maybeAttendingUser in maybeAttending:
                                if maybeAttendingUser.user.email==userEmail and maybeAttendingUser.event == getEvent:
                                    MaybeAttending.objects.get(user=getUser, event=getEvent).delete()
                                    break
                            for notAttendingUser in notAttending:
                                if notAttendingUser.user.email==userEmail and notAttendingUser.event == getEvent:
                                    NotAttending.objects.get(user=getUser, event=getEvent).delete()
                                    break
                            Attending.objects.create(user=getUser, event=getEvent)
                            attendingEvent = "Attending Event"
                            return viewEvent(request, eventID)
                
                    authorizedUser = "You are not authorized to respond to this event" 
                    return viewEvent(request, eventID)  
                
                  
                else:
                        for attendingUser in attending:
                            if attendingUser.user.email==userEmail and attendingUser.event == getEvent:
                                attended = "Already responded"
                                return viewEvent(request, eventID)
                                   
                        for maybeAttendingUser in maybeAttending:
                            if maybeAttendingUser.user.email==userEmail and maybeAttendingUser.event == getEvent:
                                MaybeAttending.objects.get(user=getUser, event=getEvent).delete()
                                break
                        for notAttendingUser in notAttending:
                            if notAttendingUser.user.email==userEmail and notAttendingUser.event == getEvent:
                                NotAttending.objects.get(user=getUser, event=getEvent).delete()
                                break
                        Attending.objects.create(user=getUser, event=getEvent)
                        attendingEvent = "Attending Event"
                        return viewEvent(request, eventID)

    except:
        logout = "Please login in"
        return render_to_response("Signup.html", locals())
    
    

        
    
def maybeAttend(request):
    """
    Author: Amina Kadry
    
    Story: C1-4
    
        this method adds the user into the MaybeAttending list of the event only if it is a private event and he is
        invited or if it is a public event 
    Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST"
    Return:
        It refreshes the page and displays a message "Maybe Attending Event"
    How the function works:
        The method is called upon clicking on the attending button which is viewed in the event page
            http://localhost:8000/maybeAttend/
    Exception:
        If the user is not logged in, he will be redirected to the homepage with a message displayed :"Please login"
        If the user clicks Maybe Attending and he is already Maybe Attending, the page will be refreshed
        If the event is private and the user click on Maybe Attending without being invited, the page will be refreshed
    
   """

    try:
        if request.session['email']== "":
            logout = "Please login in"
            return render_to_response("Signup.html", locals())
        else:
            
            print "HERE"
            attending = Attending.objects.all()
            maybeAttending = MaybeAttending.objects.all()
            notAttending = NotAttending.objects.all()
            eventID = request.session['eventid']
            print "EVENTID " + eventID
            getEvent = Event.objects.get(id=eventID)
            userEmail = request.session['email']
            events = Event.objects.all()
            publicEvents = Event.objects.filter(isPublic=True)
            for p in publicEvents:
                print "public" + p.template.eventName
            users = User.objects.all()
            invited = Invited.objects.all()
            getUser = User.objects.get(email=userEmail)
            if getEvent.isPublic != True:
                for invitedUser in invited:
                    if invitedUser.user.email == userEmail and invitedUser.event == getEvent:
                        for attendingUser in attending:
                            if attendingUser.user.email==userEmail and attendingUser.event == getEvent:
                                Attending.objects.get(user=getUser, event=getEvent).delete()
                                break
                        for maybeAttendingUser in maybeAttending:
                            if maybeAttendingUser.user.email==userEmail and maybeAttendingUser.event == getEvent:
                                maybeAttended = "Already responded"
                                return viewEvent(request, eventID)
                        for notAttendingUser in notAttending:
                            if notAttendingUser.user.email==userEmail and notAttendingUser.event == getEvent:
                                NotAttending.objects.get(user=getUser, event=getEvent).delete()
                                break
                        MaybeAttending.objects.create(user=getUser, event=getEvent)
                        maybeAttendingEvent = "Maybe Attending Event"
                        return viewEvent(request, eventID)
                        
                authorizedUser = "You are not authorized to respond to this event"  
                return viewEvent(request, eventID) 
                
            else:
                    for attendingUser in attending:
                        if attendingUser.user.email==userEmail and attendingUser.event == getEvent:
                            Attending.objects.get(user=getUser, event=getEvent).delete()
                            break
                                
                    for maybeAttendingUser in maybeAttending:
                        if maybeAttendingUser.user.email==userEmail and maybeAttendingUser.event == getEvent:
                            maybeAttended = "Already responded"
                            return viewEvent(request, eventID)
                    for notAttendingUser in notAttending:
                        if notAttendingUser.user.email==userEmail and notAttendingUser.event == getEvent:
                            NotAttending.objects.get(user=getUser, event=getEvent).delete()
                            break
                    MaybeAttending.objects.create(user=getUser, event=getEvent)
                    maybeattending = "Maybe Attending Event"
                    return viewEvent(request, eventID)
                    
                    
            
    except:
        logout = "Please login in"
        return render_to_response("Signup.html", locals())
    

  
    
def notAttend (request):
    """
    Author: Amina Kadry
    
    Story: C1-4
    
        This method adds the user into the NotAttending list of the event only if it is a private event and he is
        invited or if it is a public event 
    Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST"
    Returns:
        It refreshes the page and displays a message "Not Attending Event"
    How the function works:
        The method is called upon clicking on the Not Attending button which is viewed in the event page
        http://localhost:8000/notAttend/
    Exception:
        If the user is not logged in, he will be redirected to the homepage with a message displayed :"Please login"
        If the user clicks attending and he is already Not Attending, the page will be refreshed
        If the event is private and the user click on Not Attending without being invited, the page will be refreshed
    """
    
    try:
       if request.session['email']== "":
            logout = "Please login in"
            return render_to_response("Signup.html", locals())
       else:
            
       
            attending = Attending.objects.all()
            maybeAttending = MaybeAttending.objects.all()
            notAttending = NotAttending.objects.all()
            
            eventID = request.session['eventid']
            getEvent = Event.objects.get(id=eventID)
            userEmail = request.session['email']
            events = Event.objects.all()
            users = User.objects.all()
            invited = Invited.objects.all()
            getUser = User.objects.get(email=userEmail)
            if getEvent.isPublic != True:
                for invitedUser in invited:
                    if invitedUser.user.email == userEmail and invitedUser.event == getEvent:
                        for attendingUser in attending:
                            if attendingUser.user.email==userEmail and attendingUser.event == getEvent:
                                Attending.objects.get(user=getUser, event=getEvent).delete()
                                break
                        for maybeAttendingUser in maybeAttending:
                            if maybeAttendingUser.user.email==userEmail and maybeAttendingUser.event == getEvent:
                                MaybeAttending.objects.get(user=getUser, event=getEvent).delete()
                                break
                        for notAttendingUser in notAttending:
                            if notAttendingUser.user.email==userEmail and notAttendingUser.event == getEvent:
                                notAttended = "Already responded"
                                return viewEvent(request, eventID)
       
                        NotAttending.objects.create(user=getUser, event=getEvent)
                        notAttendingEvent = "Not Attending Event"
                        print "CREATOR " + getEvent.creator.email
                        print "USEREMAIL " + userEmail
                        return viewEvent(request, eventID)
                authorizedUser = "You are not authorized to respond to this event"   
                return viewEvent(request, eventID)
            else:
               
                    for attendingUser in attending:
                        if attendingUser.user.email==userEmail and attendingUser.event == getEvent:
                            Attending.objects.get(user=getUser, event=getEvent).delete()
                            break
                                
                    for maybeAttendingUser in maybeAttending:
                        if maybeAttendingUser.user.email==userEmail and maybeAttendingUser.event == getEvent:
                            MaybeAttending.objects.get(user=getUser, event=getEvent).delete()
                            break
                                
                    for notAttendingUser in notAttending:
                        if notAttendingUser.user.email==userEmail and notAttendingUser.event == getEvent:
                            notAttended = "Already responded"
                            return viewEvent(request, eventID)
                        
                    NotAttending.objects.create(user=getUser, event=getEvent)
                    notattendingEvent = "Not Attending Event"
                    return viewEvent(request,eventID)
                        
       
    except:
        logout = "Please login in"
        return render_to_response("Signup.html", locals())
    
         
           
           
def invite(request):
  """
  
    Author: Amina Kadry
    
    Story: C1-12
        
        This method views all users list where the creator can invite other users 
    Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST"
        
    Returns:
        Redirects to the creator event page.
        
    How the function works:
        The creator will choose the users and then click on the button invite to call the method
        http://localhost:8000/invite/
        
    Exception:
        If the user is not logged in, he will be redirected to the homepage with a message displayed:"Please login"
        If he does not choose any user, the page will be directed with a message displayed:"Please choose a user to invite"
        Returns Already invited if the creator tries to invite a user who is already invited
  """

  try:
      if emailSession['email']== "":
            logout = "Please login in"
            return render_to_response("Signup.html", locals())
      else:
            flag=False
            users = User.objects.all()
            invited = Invited.objects.all()
            usersList = []
            userEmail = emailSession['email']
            eventID = request.session['eventid']
            getEvent = Event.objects.get(id = eventID)
            
            if getEvent.creator.email==userEmail: 
                invitedList = request.POST.getlist('invite') 
                if len(invitedList)==0:
                    pleaseInvite = "Please choose a user to invite"
                    return render_to_response("Invite.html", locals())     
                for invitedUser in invitedList:
                    getUser = User.objects.get(email=invitedUser)
                    for invitedPerson in invited:
                        if invitedPerson.user==getUser and invitedPerson.event==getEvent:
                            alreadyInvited = "AlreadyInvited"
                            return render_to_response("Invite.html", locals())
                    
                            
                    newInvited = Invited.objects.create(user=getUser, event=getEvent)
                    newInvited.save()
                    flag = True
                    
                if flag:
                    afterInvitation = []
                    for invitedUser in Invited.objects.filter(event=getEvent):
                        afterInvitation.append(invitedUser.user)
                    for afterInvitationUser in afterInvitation:
                        print afterInvitationUser.email
                        return render_to_response("Invite.html", locals())
            else:
                notAuthorized = "You are not authorized to invite people to this event"
                return  viewEvent(request, eventID)
  except:
      logout = "Please login in"
      return render_to_response("Signup.html", locals())





def viewCurrentCredit(id):
    """
		Author:
			Nermeen Hashem
		Story: C4-4 
			this method calculates the current credit of the eventCreator for a certain event by 
			calculation the number of paid attendees and the amount to be paid in a certain event
		Args: 
		    it takes as an input event id from method view event
		returns :
			an HTML page containing the Event creator's current credit
		How to use this function:
			the event creator will open the event page and he will find his current credit displayed
	"""
    event = Event.objects.get(pk= id)
    paidEvents = PayedAttendees.objects.all()
    count = 0
    credit = 0
    amount =  event.template.payment.paymentAmount 
    for payer in paidEvents:
        if (payer.event ==event): 
            count = count+1
    credit = count * amount
    
    return credit



def setSocialMarekting(request):
    """
    Author:
        Nermeen Hashem
    Story: C4-12
        this method takes as an input the event creators facebook url or twitter userName or hashtag and
        and adds them to the database to help the event creator to communicate with other other Attendees using
        these social networks
    Args: 
        it takes a request, no input
    returns:
        it returns nothing 
    How to use this function:
        when the user is creating an event, he will choose a template and then he will be asked to
    check for the components he likes to add ,if he checked to add social marketing component
    an HTML page will opened requesting his facebook url ,twitter username and hashtag,
    when he enters the requested info, he will then press submit.
    """      
    if request.method == 'POST':
            facebookUrl = request.POST.get('facebookUrl')
            twitterUserName = request.POST.get('twitterUserName')
            hashTag = request.POST.get('hashTag')
            correctFacebookUrl = "http://www.facebook.com/"
            correctFacebookUrl2 = "https://www.facebook.com/"
            if facebookUrl and twitterUserName and hashTag:
                if facebookUrl[0:24] == correctFacebookUrl or facebookUrl[0:25]== correctFacebookUrl2:
                    userFacebookID = facebookUrl[24:]
                    urlFacebook= correctFacebookUrl+ userFacebookID
                    newSocialMarketing =SocialMarketing.objects.create(facebookUrl=urlFacebook, twitterUserName=twitterUserName, hashTag = hashTag)
                    newSocialMarketing.save()
                    request.session["socialMarketing"] = newSocialMarketing
                    return viewLiveStream(request)
                else:
                    failureMessage = "Please enter the correct Facebook Url."
                    return render_to_response("Social.html", {'failureMessage': failureMessage})
            elif facebookUrl and twitterUserName:
                    if facebookUrl[0:24] == correctFacebookUrl or facebookUrl[0:25]== correctFacebookUrl2:
                        userFacebookID = facebookUrl[24:]
                        urlFacebook= correctFacebookUrl+ userFacebookID
                        newSocialMarketing =SocialMarketing.objects.create(facebookUrl=urlFacebook, twitterUserName=twitterUserName)
                        newSocialMarketing.save()
                        request.session["socialMarketing"] = newSocialMarketing
                        return viewLiveStream(request)
                    else:
                        failureMessage = "Please enter the correct Facebook Url."
                        return render_to_response("Social.html", {'failureMessage': failureMessage})
            elif twitterUserName and hashTag:
                    newSocialMarketing =SocialMarketing.objects.create(twitterUserName=twitterUserName, hashTag = hashTag)
                    newSocialMarketing.save()
                    request.session["socialMarketing"] = newSocialMarketing
                    return viewLiveStream(request) 
            elif twitterUserName:
                    newSocialMarketing =SocialMarketing.objects.create(twitterUserName=twitterUserName)
                    newSocialMarketing.save()
                    request.session["socialMarketing"] = newSocialMarketing
                    return viewLiveStream(request) 
                 
            elif facebookUrl:
                if facebookUrl[0:24] == correctFacebookUrl or facebookUrl[0:25]== correctFacebookUrl2:
                    userFacebookID = facebookUrl[24:]
                    urlFacebook= correctFacebookUrl+ userFacebookID
                    newSocialMarketing =SocialMarketing.objects.create(facebookUrl=urlFacebook)
                    newSocialMarketing.save()
                    request.session["socialMarketing"] = newSocialMarketing
                    return viewLiveStream(request)
                else: 
                    failureMessage = "Please enter the correct Facebook Url."
                    return render_to_response("Social.html", {'failureMessage': failureMessage})
            elif facebookUrl and hashTag:
                if facebookUrl[0:24] == correctFacebookUrl or facebookUrl[0:25]== correctFacebookUrl2:
                    userFacebookID = facebookUrl[24:]
                    urlFacebook= correctFacebookUrl+ userFacebookID
                    newSocialMarketing =SocialMarketing.objects.create(facebookUrl=urlFacebook, hashTag = hashTag)
                    newSocialMarketing.save()
                    request.session["socialMarketing"] = newSocialMarketing
                    return viewLiveStream(request)
                else: 
                    failureMessage = "Please enter the correct Facebook Url."
                    return render_to_response("Social.html", {'failureMessage': failureMessage})
            
            elif hashTag:
                newSocialMarketing =SocialMarketing.objects.create(hashTag = hashTag)
                newSocialMarketing.save()
                request.session["socialMarketing"] = newSocialMarketing
                return viewLiveStream(request)    
                
            elif not facebookUrl and not twitterUserName and not hashTag :
                failureMessage = "please enter at least one field"
                return render_to_response("Social.html", {'failureMessage': failureMessage})

from datetime import datetime 


def editEvent(request,eventId):
    """
    Author:
         Heba El Mohandes 
    Story:
         C1-6
        This method allows the moderator to edit the event by components like the creator
    Args:

        Event_id 
        this method is initiated through "POST" which edit fields that was entered before by event creator:
        
    Returns:
        It returns the page editComponent where the moderator can edit the event and submit the new conventions.
    How to use the function:
        in order to test this function open "http:localhost/eventEdit/1/"
    """

    if 'email' not in request.session:
        return HttpResponseRedirect('/homePage/')
    if request.session['email'] == "":
        return HttpResponseRedirect('/homePage/')
    
    user = User.objects.get(email=request.session['email'])
    moderator = EventModerator.objects.filter(user=user.id,event=eventId)
    if moderator.count() == 0:
        return HttpResponseRedirect('/EventPage/'+eventId)
            
        
    if request.method == 'POST':
        event = Event.objects.get(id=eventId)
        template = CreatorTemplate.objects.get(id=event.template_id)
        template.eventName = request.POST.get('name')
        template.name = request.POST.get('name')
        date = datetime.strptime(request.POST.get('startDate'), '%Y-%m-%d')
        startdate_string = date.strftime('%Y-%m-%d')
        template.startDate = startdate_string
        date = datetime.strptime(request.POST.get('endDate'), '%Y-%m-%d')
        enddate_string = date.strftime('%Y-%m-%d')
        template.endDate = enddate_string
        template.startTime = request.POST.get('startTimeHour')+':'+request.POST.get('startTimeMinute')
        template.endTime = request.POST.get('endTimeHour')+':'+request.POST.get('endTimeMinute')
        if request.POST.get('private')=="on":
            event.visibility = 0
            event.isPublic = 0
        else:
            event.visibility = 1
            event.isPublic = 1
        event.save()
        template.save()        
        
        return HttpResponseRedirect('/EventPage/'+eventId)
        
    else:
        event = Event.objects.get(id=eventId)
        template = CreatorTemplate.objects.get(id=event.template_id)
        startDate = template.startDate.strftime('%Y-%m-%d')
        endDate = template.endDate.strftime('%Y-%m-%d')
        startTimeHour = template.startTime.hour
        startTimeMinute = template.startTime.minute
        endTimeHour = template.endTime.hour
        endTimeMinute = template.endTime.minute
        return render_to_response('EditEvent.html',locals(),RequestContext(request))


def suggestComponent(request):

    """ 
    Author:
        Heba El Mohandes
     Story:
         C1-8
    This method only allows the user to suggest component to the admin by selecting the link Suggest Component in the UserEvent.html,CreatorEvent.html and ModeratorEvent.html
    Args:
        no inputs
         this method is initiated through "POST" to allow the user to ente name and description of what he want to suggest to the admin 
    Returns:
        Returns page that allows the user to suggest component in  (SuggestComponent.html) 
    How to use the funtion:
        Type the localhost "http://localhost:8000/SuggestComponent/"
    """
    
    if 'email' not in request.session:
        return HttpResponseRedirect('/homePage/')
    if request.session['email'] == "":
        return HttpResponseRedirect('/homePage/')
    
    if request.method == 'POST':
        component = Component(title=request.POST.get('name'),description=request.POST.get('desc'),approved=0,rejected=0) 
        component.save()
        emailSession['email'] = request.session['email']
        return showDashboard(request)
    else:
        return render_to_response('SuggestComponent.html',RequestContext(request))


def viewComponent(request,componentId):
    """ 
    Author:
        Heba El Mohandes
     Story:
         C1-10
    This method only allows the admin to view suggested component by the user by clicking the button view in the admin page
    Args:
        the component id 
        
    Returns:
        Returns page that allows the admin to view the suggested component in ViewComponent.html
    How to use the funtion:
        Type the localhost "http://localhost:8000/ViewComponent/"
    """
    if request.user.is_staff == False:
        return showDashboard(request)
    
    component= Component.objects.get(id=componentId)
    return render_to_response("ViewComponent.html", locals())

def viewAboutUs(request):
    """
    Author: Ahmed Taher C5-01
    this method  displays all the information about the  website to the users when the user clicks on the button.
        Args: 
            No arguments defined
        Returns: 
            HTML page that displays all the information of the website.
        How to use this function:
            After logging on, the user will click on the button shown AboutUs in order to redirect him to the page having the AboutUs of the website.
	"""

    return render_to_response('AboutUs.html' ,locals())


def viewFaqs(request):
    """
	
    Author: Sebbah Safey C5-02
    This method view all questions and answers for the users
        Args: 
            No arguments defined
        Returns: 
           HTML page containing the questions and answers
        How to use this function:
            Type "127.0.0.1:8000/Faqs/"
	"""
    Faqs=Faq.objects.all()
    return render_to_response('Faqs.html' ,{ 'Faqs': Faqs})


 
def viewContactUs(request):
    return render_to_response('ContactUs.html' ,RequestContext(request))

    """
    
    Author: Sebbah Safey C5-05
    This method views the contactus form
        Args: 
            No arguments defined
        Returns: 
           HTML page containing the form
        How to use this function:
            Type "127.0.0.1:8000/Contactus/"
    """
  
def  showDashboard(request):
    """
    Author: Miran Shahin C3-13
    
    the method retrieves the most recent upcoming 3 events that the user
    created or will attend and DISPLAYS it in the home page as soon as the user
    logs in
    
    Args:
    no parameters
    
    Returns:
    
    a list of events that will redirect the user to the event page they wish to
    access
    
    how to use the function:
    
    in order to test this function open http:localhost/DashBoardHome/ and log
    in and create or attend any event
    """
    try:
        if emailSession['email']== "":
            logOut = "Please login in"
            return render_to_response("Signup.html", locals())
        else: 
            flagSystemModerator = False
            sessionMail = emailSession['email']
            user = User.objects.get(email = sessionMail)
            createdEventsList = []
            attendingEventsList = []
            invitedEventsList = []
            moderatedEventsList = []
            bookmarkEventsList = []
            createdList = Event.objects.filter(creator = user)
            attendingList = Attending.objects.filter(user = user)
            invitedList = Invited.objects.filter(user = user)
            moderatedList = EventModerator.objects.filter(user = user)
            bookmarkList = Bookmark.objects.filter(user=user)
            countCreatedEventsList = len(createdList)
            countBookmarkedEventsList= len(bookmarkList)
            if user.SystemModerator:
                flagSystemModerator = True
            
            for create in createdList:
                    if(create.template.startDate >= date.today()):
                        createdEventsList.append(create)
            createdEventsList.reverse()          
            createdEventsList.sort(key=operator.attrgetter('template.startDate'))
            
            for attend in attendingList:
                    if(attend.event.template.startDate >=date.today()):
                        attendingEventsList.append(attend.event)
            attendingEventsList.reverse()
            countAttendingEventsList = len(attendingEventsList)
            attendingEventsList.sort(key=operator.attrgetter('template.startDate'))
        
            
            for invite in invitedList:
                    if(invite.event.template.startDate >=date.today()):
                        invitedEventsList.append(invite.event)
            invitedEventsList.reverse()
            countInvitedEventsList = len(invitedEventsList)
            invitedEventsList.sort(key=operator.attrgetter('template.startDate'))
        
            for moderate in moderatedList:
                    if(moderate.event.template.startDate >=date.today()):
                        moderatedEventsList.append(moderate.event)
            moderatedEventsList.reverse()
            countModeratedEventsList = len(moderatedList)
            moderatedEventsList.sort(key=operator.attrgetter('template.startDate'))
        
            for bookmark in bookmarkList:
                bookmarkEventsList.append(bookmark.event)
            return render_to_response('DashboardHome.html', locals())
    except:
        logOut = "Please login in"
        return render_to_response("Signup.html", locals())

def showAllCreatedEvents (request):
    """
    Author: Miran Shahin C3-13
    the method retrieves a sorted list of all the events that the user created
    Args:
    no arguments taken
    Returns: 
    redirected to a page with a list of all the events that the user created where he can click on any event to open its page
    how to use the function:
    open http://localhost/DashBoardHome/ after logging in and creating or attending any event 
    then click the button see all
    """
    try:
        if emailSession['email']== "":
            logOut = "Please login in"
            return render_to_response("Signup.html", locals())
        else: 
            flag = True
            sessionMail = emailSession['email']
            user = User.objects.get(email = sessionMail)
            allCreatedEvents = list(Event.objects.filter(creator = user))
            allCreatedEvents.reverse()
            allCreatedEvents.sort(key=operator.attrgetter('template.startDate'))
            return render_to_response('CreatedEvents.html', locals())
    except:
        logOut = "Please login in"
        return render_to_response("Signup.html", locals())

def showAllAttendingEvents (request):
    """
    Author: Miran Shahin C3-13
    the method retrieves a sorted list of all the events that the user will attend
    Args:
    no arguments taken
    Returns: 
    There is no return, however the user is redirected to a page with a list of all the events that they are attending. Then the user wil be able to access any of those events by clicking on the event itself
    how to use the function:
    open http://localhost/DashBoardHome/ 
    after logging in click the button see all
    """
    try:
        if emailSession['email']== "":
            logOut = "Please login in"
            return render_to_response("Signup.html", locals())
        else: 
            flag = True
            sessionMail = emailSession['email']
            user = User.objects.get(email = sessionMail)
            allAttendingEvents =[]
            tempAllAttendingEvents = Attending.objects.filter(user = user)
            for event in tempAllAttendingEvents:
                if(event.event.template.startDate >=date.today()):
                    allAttendingEvents.append(event.event)
            allAttendingEvents.reverse()
            allAttendingEvents.sort(key=operator.attrgetter('template.startDate'))
            return render_to_response('AttendingEvents.html', locals()) 
    except:
        logOut = "Please login in"
        return render_to_response("Signup.html", locals())

def showAllInvitedEvents (request):
    """
    Author: Miran Shahin C3-13
    the method retrieves a sorted list of all the events that the user is invited to 
    Args:
         no arguments taken
    Returns: 
        redirected to a page with a list of all the events that the user is invited to where he can click on any event to open its page
    how to use the function:
        open http://localhost/DashBoardHome/ after logging in and creating, attending or invited to any event 
        then click the buttin see all
    """
    try:
        if emailSession['email']== "":
            logOut = "Please login in"
            return render_to_response("Signup.html", locals())
        else: 
            flag = True
            allInvitedEvents =[]
            sessionMail = emailSession['email']
            user = User.objects.get(email = sessionMail)
            tempAllInvitedEvents = Invited.objects.filter(user = user)
            for event in tempAllInvitedEvents:
                if(event.event.template.startDate >=date.today()):
                    allInvitedEvents.append(event.event)
            allInvitedEvents.reverse()
            allInvitedEvents.sort(key=operator.attrgetter('template.startDate'))
            return render_to_response('InvitedEvents.html', locals())
    except:
        logOut = "Please login in"
        return render_to_response("Signup.html", locals()) 

def showModeratedEvents (request):
    """
    Author: Miran Shahin C3-13
    the method retrieves a sorted list of all the events that the user is a moderator to 
    Args:
         no arguments taken
    Returns: 
        redirected to a page with a list of all the events that the user is a moderator to where he can click on any event to open its page
    how to use the function:
        open http://localhost/DashBoardHome/ after logging in and creating, attending or invited to any event 
        then click the button see all
    """
    try:
        if emailSession['email']== "":
            logOut = "Please login in"
            return render_to_response("Signup.html", locals())
        else:
            flag = True
            allModeratedEvents =[]
            sessionMail = emailSession['email']
            user = User.objects.get(email = sessionMail)
            tempAllModeratedEvents = EventModerator.objects.filter(user = user)
            for event in tempAllModeratedEvents:
                    allModeratedEvents.append(event.event)
            allModeratedEvents.reverse()
            allModeratedEvents.sort(key=operator.attrgetter('template.startDate'))
            return render_to_response('ModeratedEvents.html', locals()) 
    except:
        logOut = "Please login in"
        return render_to_response("Signup.html", locals()) 
def searchInCreated(request):
    """
    Author: Miran Shahin C3-17
    the method allows the user to search throw his created events list by the event name
    Args:
         no arguments taken
    Returns: 
    refreshes the same page and adding the results of the search in it. if no results found, 
    then a 'no results found' message will be shown      
    how to use the function:
        open http://localhost/DashBoardHome/ after logging in and creating, attending or invited to any event 
        then click the buttin see all, type in the search box then press search
    """
    flag = False
    searchKey = request.POST.get('search', '')
    sessionMail = emailSession['email']
    user = User.objects.get(email = sessionMail)
    createdList = Event.objects.filter(creator = user)
    eventsList = []
    for event in createdList :
        if searchKey.lower() in event.template.eventName.lower():
            eventsList.append(event)
                
    if not eventsList:
        result = "Sorry, No Results Found"
        return render_to_response("CreatedEvents.html" , locals(),RequestContext(request)) 
    else:
        return render_to_response("CreatedEvents.html" , locals(),RequestContext(request)) 
 
     
        
def searchInAttending(request):
    """
    Author: Miran Shahin C3-17
    the method allows the user to search throw his attending events list by the event name
    Args:
         no arguments taken
    Returns: 
    refreshes the same page and adding the results of the search in it. if no results found, 
    then a 'no results found' message will be shown      
    how to use the function:
        open http://localhost/DashBoardHome/ after logging in and creating, attending or invited to any event 
        then click the buttin see all, type in the search box then press search
    """
    flag = False
    searchKey = request.POST.get('search', '')
    sessionMail = emailSession['email']
    user = User.objects.get(email = sessionMail)
    attendingList = Attending.objects.filter(user = user)
    eventsList = []
    for event in attendingList :
        if searchKey.lower() in event.event.template.eventName.lower():
            eventsList.append(event.event)
                
    if not eventsList:
        result = "Sorry, No Results Found"
        return render_to_response("AttendingEvents.html" , locals(),RequestContext(request))
    else:
        return render_to_response("AttendingEvents.html" , locals(),RequestContext(request))
  
def searchInInvited(request):
    """
    Author: Miran Shahin C3-17
    the method allows the user to search throw his invited events list by the event name
    Args:

         no arguments taken
    Returns: 
    refreshes the same page and adding the results of the search in it. if no results found, 
    then a 'no results found' message will be shown      
    how to use the function:
        open http://localhost/DashBoardHome/ after logging in and creating, attending or invited to any event 
        then click the buttin see all, type in the search box then press search
    """
    flag = False
    searchKey = request.POST.get('search', '')
    sessionMail = emailSession['email']
    user = User.objects.get(email = sessionMail)
    invitedList = Invited.objects.filter(user = user)
    eventsList = []
    for event in invitedList :
        if searchKey.lower() in event.event.template.eventName.lower():
            eventsList.append(event.event)
                
    if not eventsList:
        result = "Sorry, No Results Found"
        return render_to_response("InvitedEvents.html" , locals(),RequestContext(request))
    else:
        return render_to_response("InvitedEvents.html" , locals(),RequestContext(request))
def showBookmarkedEvents(request):
	"""
	Author: Fouad Hesham Said 
	Story: C1-S15
		This method returns all bookmarked events to be shown in the dashbaord home
	Args:
		This method takes no arguments
	Returns:
		This method returns all bookmarked events to be shown in the dashbaord home
	How to use the function:
		http://localhost:8000/showBookmarkedEvents
	"""
	flag = True
	sessionMail = request.session['email']
	user = User.objects.get(email=sessionMail)
	allBookmarkedEvents = []
	tempAllBookmarkedEvents = Bookmark.objects.filter(user=user)
	for event in tempAllBookmarkedEvents:
		allBookmarkedEvents.append(event.event)
	return render_to_response("BookmarkedEvents.html", locals())

def searchInModerated(request):
    """
    Author: Miran Shahin C3-17
    the method allows the user to search throw his moderated events list by the event name
    Args:
         no arguments taken
    Returns: 
    refreshes the same page and adding the results of the search in it. if no results found, 
    then a 'no results found' message will be shown      
    how to use the function:
        open http://localhost/DashBoardHome/ after logging in and creating, attending or invited to any event 
        then click the buttin see all, type in the search box then press search
    """
    flag = False
    searchKey = request.POST.get('search', '')
    sessionMail = emailSession['email']
    user = User.objects.get(email = sessionMail)
    moderatedList = EventModerator.objects.filter(user = user)
    eventsList = []
    for event in moderatedList :
        if searchKey.lower() in event.event.template.eventName.lower():
            eventsList.append(event.event)
                
    if not eventsList:
        result = "Sorry, No Results Found"
        return render_to_response("ModeratedEvents.html" , locals(),RequestContext(request))
    else:
        return render_to_response("ModeratedEvents.html" , locals(),RequestContext(request))
    
def showTempEvent (request, id): 
    """
    def showTempEvent (request, id):  
    this method redirects the user to the event page the user clicks on
    Args:
        id (Integer) : event ID 
    Returns:
        redirects to the method viewEvent(request,id) which shows the event page
    how to use the function:
        open the dashboard http://localhost/DashBoardHome/ click on any of the events that appear
        You will be directed to the event page through this method
    """
    return  viewEvent(request , id)


def viewTerms (request):
	"""
    Author: Yomna Osama C5-09
    Views the terms and conditions when the user clicks on Terms and Conditions
    Args: 
    No arguments defined
    Returns: 
    Terms&Conditions html page
    How to use this function:
    Type "127.0.0.1:8000/Terms&Conditions/"
    """
	terms = TermsAndCondition.objects.all()
	return render_to_response("Terms&Conditions.html", locals())
 
def viewNews (request):
	"""
    Author: Yomna Osama C5-03
    The method Views the News and Updates when the user clicks on News and Updates
    Args: 
    No arguments defined
    Returns: 
    News html page
    How to use this function:
    Type "127.0.0.1:8000/News/"
    """ 
	news = NewsAndUpdate.objects.all()
	return render_to_response("News.html", locals())

    
def viewInstructions(request):
	"""
    Author: Ahmed Taher C5-04
    this method  displays all the instructions of the website to the users 
        Args: 
            No arguments defined
        Returns: 
            HTML page that displays all the instructions of the website.
        How to use this function:
            After logging on, the user will click on the button shown Instructions in order to redirect him to the page having the instructions of the website.
    """ 
	
	Instructions = KnowledgeStore.objects.all()
	return render_to_response('ViewInstructions.html',locals())
    


    
    


def autoCompleteSearch(request):
    """
	Author: 
		Dalia Hosny C5-07
    This method is used to compare the search term retrieved from the search box in the html page 
    and retrieve all the events that have the same letters as the ones entered in the search key
    and return the result to the html page as an autocomplete function
    Args:
        The method takes no arugment, only the request that the html page sends
    Returns:
        The method returns a simplejson that displays the data as an autocomplete function for the textbox
        of the search engine
    How to use the funtion:
        Works when a user types a search key in the textbox of the search engine
    """
    flag = True
    term = request.GET.get('term')
    res = []
    if flag == True:
        events = CreatorTemplate.objects.filter(eventName__icontains=term)
        for items in events:
            dict = {'id':items.id, 'label':items.eventName}
            res.append(dict)
        if flag == True:
            events = CreatorTemplate.objects.filter(name__icontains=term)
            for items in events:
                dict2 = {'id':items.id, 'label':items.name}
                res.append(dict2)
            if flag == True:
                location = Locations.objects.filter(city__icontains=term)
                for items in location:
                    dict3 = {'id':items.id, 'label':items.city}
                    res.append(dict3)
                if flag == True:
					location = Locations.objects.filter(Country__icontains=term)
					for items in location:
						dict4 = {'id':items.id, 'label':items.Country}
						res.append(dict4)
    return HttpResponse(simplejson.dumps(res))

def goToPage(request, id):
    """
	Author: 
		Dalia Hosny C5-07
    This method is used to direct to a specific Event page when clicked from the results list
    Args:
        The method takes the "id" of the Event page as an argument
    Returns:
        The method returns an HTML page for the specific event page selected
    How to use the funtion:
        Works when an Event is clicked
    """
    idEvent = Event.objects.get(pk=id)
    return viewEvent(request, id)

def searchEngine(request):
    """
	Author: 
		Dalia Hosny C5-07
    Search the events table to retrieve a list of events based on a certain search criteria
    Args: 
        No arguments defined
    Returns: 
        HTML page that displays Events' Name, Location, Category, Creator and Visibility
        If no results were found, an Http resonse is returned with a "No results found" Statement
    How to use this function:
        When the Engine is opened, After the user chooses the inputs, on the Search click,
    This method is called to retrieve Results
    """
    searchCategory = request.POST.get('Categories', '')
    searchKey = request.POST.get('search', '')
    
    if searchCategory =="Name":
        eventsList = []
        for event in Event.objects.filter(isPublic=True):
            if searchKey.lower() in event.template.eventName.lower():
                eventsList.append(event)
        if not eventsList:
            return HttpResponse ("Sorry, There are no Results Found with the event name you are searching for")
        else:
            return render_to_response("ResultsEvents.html" , locals(),RequestContext(request))
        
    else:
        if searchCategory =="Location":
            eventsList = []
            for location in Locations.objects.all():
                if (searchKey.lower() in location.Street.lower()) or (searchKey.lower() in location.city.lower()) or (searchKey.lower() in location.Country.lower()):
                    if (location.event.isPublic == True):
                        eventsList.append(location.event)
            if not eventsList:
                return HttpResponse ("Sorry, There are no Results Found with the location you are searching for")
            else:
                return render_to_response("ResultsEvents.html" , locals())  
        else:
            if searchCategory =="Tag":
                eventsList = []
                for event in Event.objects.filter(isPublic=True):
                    if searchKey.lower() in event.template.socialMarketing.hashTag.lower():
                        eventsList.append(event)
                if not eventsList:
                    return HttpResponse ("Sorry, There are no Results Found with the hashtag you are searching for")
                else:
                    return render_to_response("ResultsEvents.html" , locals())
            else:
                if searchCategory =="Category":
                    eventsList = []
                    for event in Event.objects.filter(isPublic=True):
                        if searchKey.lower() in event.template.name.lower():
                            eventsList.append(event)
                    if not eventsList:
						return HttpResponse ("Sorry, There are no Results Found with the Category you are searching for")
                    else:
						return render_to_response("ResultsEvents.html" , locals())



def viewTemplates (request):
    '''		
	Author: Sherine Nouh

    Story: C2-2

    The method displays all the available templates of Eventati website from the database to the event creator. 
    Args:	
	   There are no arguments for the method however it uses the POST method to display all templates available after the user clicks on create event button 
    Returns:
           The method has no return value however it redirects the user to a page displaying a list of available templates.
    How to use the function:
           The user creates an event and then the user views the available templates.
	       http://127.0.0.1:8000/viewTemplates/
	'''
    variables= {"templates":EventTemplate.objects.all()}
    return render_to_response("ListOfTemplates.html",variables,context_instance=RequestContext(request))    


   
def viewPayment(request):
    """
    Author: Sherine Nouh
    Story: C2-13
    The method checks if the location component was chosen it saves it to the current template and the current event then checks if the payment component is chosen it redirects the creator to the payment page else it calls the viewAgenda method
    Args:
    The method takes not input however it uses a post method to determine which component has been checked
    Returns:
    The method has no returns however it redirects the creator to the payment page if the payment component is selected otherwise viewAgenda method is called             
    How the function works:
    The method is called upon clicking on the submit button of template page or the previous component that has been checked
    http://127.0.0.1:8000/payment/
    """
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
    template = currentEvent.template
    selectedComponents = SelectedComponents.objects.filter(template=template)
    newChoices = NewChoices.objects.filter(template=template)
   # for item in selectedComponents:
   #  if(item.name=="Location"): 
#    newChoices=request.session['newChoices']
    for i in newChoices:
        if(i.name=="Location"):
            return viewEvent(request,currentEventId)
    for item in selectedComponents:       
        if(item.name=="Payment"):
            return render_to_response("Payment.html",locals(),context_instance=RequestContext(request))     
    
    return viewAgenda(request)

 
def viewAgenda(request):
    """
    Author: Sherine Nouh
    Story: C2-13
    The method checks if the payment component was chosen it saves it to the current template and the current event then checks if the payment component is chosen it redirects the creator to the agenda page else it calls the viewMedia method
    Args:
    The method takes not input however it uses a post method to determine which component has been checked
    Returns:
    The method has no returns however it redirects the creator to the agenda page if the agenda component is selected otherwise viewMedia method is called             
    How the function works:
    The method is called upon clicking on the submit button of template page or the previous component that has been checked
    http://127.0.0.1:8000/assignPayment/
    """
#    newChoices=request.session['newChoices']
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
    template = currentEvent.template
    selectedComponents = SelectedComponents.objects.filter(template=template)
    newChoices = NewChoices.objects.filter(template=template)
    #selectedComponents=request.session['selectedComponents']
    
    for item in selectedComponents:
        if (item.name == "Payment"):
            payment = request.session['Payment']
            payment.save()
            eventid=request.session['eventid']
            event=Event.objects.get(pk=eventid)
            template=event.template
            template.payment = payment
            template.save()
            event.template=template
            request.session['template'] = template
            event.save()     
            request.session['Event']=event
  #  newChoices=request.session['newChoices']
    for i in newChoices:
        if(i.name=="Payment"):
            return viewEvent(request,currentEventId)
    for item in selectedComponents:     
        if(item.name=="Agenda"):
                return render_to_response("Agenda.html",locals(),context_instance=RequestContext(request)) 
    return viewMedia(request)




def viewMedia(request):
    """
    Author: Sherine Nouh
    Story: C2-13
    The method checks if the media component is chosen then it redirects the creator to the media page else it calls the viewSocialMarketing method
    Args:
    The method takes not input however it uses a post method to determine which component has been checked
    Returns:
    The method has no returns however it redirects the creator to the media page if the agenda component is selected otherwise viewSocialMarkting method is called             
    How the function works:
    The method is called upon clicking on the submit button of template page or the previous component that has been checked
    http://127.0.0.1:8000/media/
    """

    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
    template = currentEvent.template
    selectedComponents = SelectedComponents.objects.filter(template=template)
    newChoices = NewChoices.objects.filter(template=template)   
    for item in selectedComponents:
        if(item.name == "Agenda"):
            agenda = request.session['agenda']
            agenda.save()
            eventid=request.session['eventid']
            event = Event.objects.get(pk = eventid)
            template=event.template
            print template.id
            template.agenda = agenda
            template.save()
            event.template = template
            request.session['template'] = template   
            event.save()
            request.session['Event']=event
#    newChoices=request.session['newChoices']        
    for i in newChoices:
        if(i.name=="Agenda"):
            return viewEvent(request,currentEventId)                
    for item in selectedComponents:
        if(item.name=="Media"):
            photoForm = UploadPhoto()
            videoForm = UploadVideo()
            return render_to_response("Media.html",locals(),context_instance=RequestContext(request))
    return viewSocialMarketing(request)  


def viewSocialMarketing(request):
    """
    Author: Sherine Nouh    
    Story: C2-13
    The method checks if the media component was chosen it saves it to the current template and the current event then it checks if the socialMarketing component is chosen it redirects the creator to the socialMarketing page else it calls the viewLiveStream method
    Args:
    The method takes not input however it uses a post method to determine which component has been checked
    Returns:
    The method has no returns however it redirects the creator to the socialMarketing page if the socialMarketing component is selected otherwise viewLiveStream method is called             
    How the function works:
    The method is called upon clicking on the submit button of template page or the previous component that has been checked
    http://127.0.0.1:8000/socialmarketing/
    """
   # selectedComponents=request.session['selectedComponents']
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
    template = currentEvent.template
    selectedComponents = SelectedComponents.objects.filter(template=template)
    newChoices = NewChoices.objects.filter(template=template)
#    template = request.session['template']
   # for item in selectedComponents:
   #  if(item.name=="Media"):
#    newChoices=request.session['newChoices']        
    for i in newChoices:
        if(i.name=="Media"):
            return viewEvent(request,currentEventId)             
    for item in selectedComponents:
        if(item.name=="Social Marketing"): 
            return render_to_response("social.html",locals(),context_instance=RequestContext(request))
    return viewLiveStream(request)

def viewLiveStream(request):
    """
    Author: Sherine Nouh
    Story: C2-13
    The method checks if the social marketing component was chosen it saves it to the current template and the current event then it checks if the liveStream component is chosen then it redirects the creator to the liveStream page else it calls the  method
    Args:
    The method takes not input however it uses a post method to determine which component has been checked
    Returns:
    The method has no returns however it redirects the creator to the liveStream page if the liveStream component is selected otherwise viewSuccesss method is called             
    How the function works:
    The method is called upon clicking on the submit button of template page or the previous component that has been checked
    http://127.0.0.1:8000/social/
    """
  #  selectedComponents=request.session['selectedComponents']
  #  template = request.session["template"]
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
    template = currentEvent.template
    selectedComponents = SelectedComponents.objects.filter(template=template)
    newChoices = NewChoices.objects.filter(template=template)
#    template = request.session['template']
    for item in selectedComponents:
        
        if(item.name=="Social Marketing"):
            socialMarekting = request.session["socialMarketing"]
            socialMarekting.save()
            eventid=request.session['eventid']
            event = Event.objects.get(pk = eventid)
            template=event.template
            template.socialMarketing = socialMarekting
            template.save()
            event.template=template
            request.session['template']=template
            event.save()     
            request.session['Event']=event
#    newChoices=request.session['newChoices']        
    for i in newChoices:
        if(i.name=="Social Marketing"):
            return viewEvent(request,currentEventId)            
    for item in selectedComponents:   
        if(item.name=="Live Stream"):
            
            return render_to_response("LiveStream.html",locals(),context_instance=RequestContext(request)) 
    return viewSuccess(request)

def viewSuccess(request):
    """
    Author: Sherine Nouh
    Story: C2-13
    The method checks if the livestream component was chosen it saves it to the current template and the current event then it redirects the creator to a page notifying him that he has completed template requitments
    Args:    
    The method takes not input however it uses a post method.
    Returns:    
    The method has no returns however it redirects the creator to the success page to tell him that he has completed needed requirments
    How the function works:
    The method is called upon clicking on the submit button of last chosen component
    http://127.0.0.1:8000/success/
    
    """
    #selectedComponents=request.session['selectedComponents']
    #template = request.session["template"]
#    newChoices=request.session['newChoices']
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
    template = currentEvent.template
    selectedComponents = SelectedComponents.objects.filter(template=template)
    newChoices = NewChoices.objects.filter(template=template)
#    template = request.session["template"]
    
    for item in selectedComponents:
        if(item.name=="Live Stream"):
            liveStream = request.session["livestream"]
            liveStream.save()
            eventid=request.session['eventid']
            event=Event.objects.get(pk=eventid)
            template=event.template
            template.liveStream = liveStream
            template.save()
            event.template=template
            request.session['template'] = template
            event.save()     
            request.session['Event']=event
#    newChoices=request.session['newChoices']
    for i in newChoices:
        if(i.name=="Live Stream"):
            return viewEvent(request,currentEventId) 
            
            
    #eventId = request.session["eventId"]
    return render_to_response("Success.html",locals(),context_instance=RequestContext(request))

    
    
    
def addEventComponents(request):
    """
    Author: Ola Magdy
    def addEventComponents(request):
    The method gets the name of the template that the user selected and creates new creator template with default values attributes and creates the event and finally redirect the creator to the components page
    Args
    This method takes no attributes however it uses the POST method to retrieve the name of the template selected
    Returns
    There is no output however it redirects the user to the components page
    through render.response
    """
    
    if request.method == "POST":
        templateName= request.POST.get('name')
        #print(templateName)  
        
        payment=Payment.objects.create(paymentAmount=-1)
        media=Media.objects.create()
        location=Location.objects.create(name="not chosen")
        agenda=Agenda.objects.create(title="not chosen")
        livestream=LiveStream.objects.create(channel="not chosen")
        socialMarketing = SocialMarketing.objects.create()
        
        template= CreatorTemplate.objects.create(name=templateName,payment=payment,location=location,agenda=agenda,media=media, liveStream=livestream, socialMarketing=socialMarketing)
        template.save()
        
        request.session['template']=template
        userEmail = request.session['email']
        creator = User.objects.get(email=userEmail)
        
        event=Event.objects.create(template=template,creator=creator,countShare=0)
        request.session['Event']=event
        request.session["eventid"]=event.id
        newViewerCount = PageViewers.objects.create(user = creator, event = event)
        newViewerCount.save()
        newpagecounter = PageCounter.objects.create(event = event, pageCounter =0) 
        newpagecounter.save()
        list = List.objects.create(event = event , createdByUser = "no")
        list.save()
        items = viewList(list)
        days= []
        for day in range(1,32):
            days.append(day)
        
        years= []
        for year in range(2012,2015):
            years.append(year)    
    
    
    
    return render_to_response("Components.html",locals(),context_instance=RequestContext(request))


        
def submitComponents(request):
    """
    Author: Sherine Nouh
    submitComponents "part 1"
    Story: C2-13
    The method checks the components selected by the creator, creates a new component of this type, adds it to a new creatorTemplate and then  checks if the creator has chosen the location component it redirects him to the location component form else it calls the viewAgenda method
    Args:
    The method takes not input however it uses a post method to determine which component has been checked    
    Returns:
    The method has no returns however it redirects the creator to the location page if the location component is selected otherwise agendaview method is called         
    How the function works:
    The method is called upon clicking on the submit button in the template page
    http://127.0.0.1:8000/location/
    """
        
    """
    Author: Ola Magdy
    def submitComponents "part 2"
     the method checks the name of the template chosen and views basic attributes like date and time, additional attributes and checks the recommended components accordingly
    Args
        it takes no input but uses the POST method to update the date and time and additional attributes
    Returns
        it redirects the creator to the first chosen component
    """

    template=request.session['template']
    
    if request.method == "POST":
        eventName = request.POST.get('EventName')
        
        startTime= request.POST.get('StartTime')
        endTime= request.POST.get('EndTime') 
        
        template.eventName = eventName
        startDate=request.POST.get('sDay')
        endDate=request.POST.get('eDay')
        
        if template.name== "Create your own template":
            description = request.POST.get('description')
            template.description = description
        template.save()  
        
        if template.name== "Wedding":
            brideName = request.POST.get('BrideName')
            groomName = request.POST.get('GroomName')
            template.brideName = brideName
            template.groomName = groomName
            
        if template.name== "Engagement":
            brideName = request.POST.get('BrideName')
            groomName = request.POST.get('GroomName')
            template.brideName = brideName
            template.groomName = groomName    
        
        if template.name== "Birthday":
            birthdayOwner = request.POST.get('BirthdayOwner')
            template.birthdayOwner = birthdayOwner
        
        if template.name== "Concert":
            singerName = request.POST.get('SingerName')
            template.SingerName = singerName
        
        if template.name== "Charity":
            charityType = request.POST.get('CharityType')
            template.charityType = charityType
        template.save()
    
        template.startDate=startDate
        print(template.startDate)
        template.endDate=endDate
        print(template.endDate)
        
     
           
        template.startTime = startTime
        template.endTime = endTime
            
        if request.POST.get('eventStatus', False):
            event=request.session["Event"]
            print (event.isPublic)
            event.isPublic=True
            print (event.isPublic)
            event.save()
            
        
#        newChoices=[]
#        request.session['newChoices']=newChoices
        Choices= NewChoices.objects.create(template=template)
        
        
        selectedComponents= request.POST.getlist('component')
        request.session['selectedComponents']=selectedComponents
        for item in selectedComponents:
            newComponent= SelectedComponents.objects.create(template=template)
            newComponent.save()
            if(item=="Location"):    
                location= Location(name="to be decided")
                location.save()
                template.location=location
                template.save()
                request.session['template']=template 
                newComponent.name="Location"
                newComponent.save()
                
            if(item=="Payment"):
                pay=Payment.objects.create(paymentAmount=0) 
                pay.save()
                request.session['Payment']=pay
                template.payment=pay
                template.save()
                request.session['template']=template 
                newComponent.name="Payment"
                newComponent.save()
                
            if(item=="Media"):
#                media=Media()
#                media.save()
#                request.session['Media']=media
#                template.media=media
                template.save()
                request.session['template']=template 
                newComponent.name="Media"
                newComponent.save()  
                print "Media"
                
            if(item=="Agenda"):
                a=Agenda(title="to be decided")
                a.save()
                request.session['agenda']=a
                template.agenda=a
                template.save()
                request.session['template']=template
                newComponent.name="Agenda"
                newComponent.save()
                
            if(item=="Social Marketing"):
                socialmarketing=SocialMarketing()
                socialmarketing.save()
                request.session['socialMarketing']=socialmarketing
                template.socialmarketing=socialmarketing
                template.save()
                request.session['template']=template 
                newComponent.name="Social Marketing"
                newComponent.save()
                
            if(item=="Live Stream"):
                livestream=LiveStream(channel="to be decided")
                livestream.save()
                request.session['livestream']=livestream
                template.livestream=livestream
                template.save() 
                request.session['template']=template 
                newComponent.name="Live Stream"
                newComponent.save()
        request.session['template']=template  
        event=request.session['Event']
        event.template=template
        event.save()     
        request.session['Event']=event
    selectedComponents=SelectedComponents.objects.filter(template=event.template) 
    newChoices = NewChoices.objects.filter(template=template)
    for i in newChoices:
        if(i.name=="Location"):
            return viewEventAfterLaunch(request)
    for item in selectedComponents:       
            if(item.name=="Location"): 
                return render_to_response("CLocation.html",locals(),context_instance=RequestContext(request))     
        
    return viewPayment(request)

	
def viewEditLocation(request):
        """
        Author: Ola Magdy
        Story: C2-14
        def viewEditLocation(request):
        the method redirects the creator who wants to edit the location of his event to the edit location page that retrieves from him the new place and update it in the event
        Args
        it takes no input however it works by request when the clicks on edit location
        Returns
        it redirects the creator to the edit location page
        """
        return render_to_response("EditLocation.html",locals(),context_instance=RequestContext(request))   


def editLocation(request):
        """
        Author: Ola Magdy
        Story: C2-14
        def editLocation(request):
        The method edits the location of the event from the event page after the event was launched
        it retrieves the updated place value from the edit location page the value of the location in the creator template is replaced by the updated place then the event page is reloaded with the new location
        Args
        This method takes no attributes however it uses the POST method which retrieves from the user
        The building number:(integer)
        The street:(str)
        The City: (str)
        The Country: (str)
        Returns
        There is no output however it returns the user back to the event page with the edited location on the map
        through render.response
        """
        currentEventId=request.session["eventid"]
        currentEvent = Event.objects.get(pk = currentEventId)
        template=currentEvent.template
        currentComponents= SelectedComponents.objects.filter(template=template)
        location = Locations.objects.get(event = currentEvent)
        for component in currentComponents:
            if component.name =="Location":
                if request.method == "POST":
                    newBlockNumber = request.POST.get('bno','')
                    newStreet = request.POST.get('st','')
                    newCity = request.POST.get('city','')
                    newCountry = request.POST.get('country','')
                    location.BlockNumber = newBlockNumber
                    location.Street = newStreet
                    location.city = newCity
                    location.Country = newCountry
                    location.save()                    
                    return viewEvent(request, currentEventId)
                return render_to_response("EditLocation.html")


def viewEditPayment(request):
        """
        Author: Ola Magdy
        Story: C2-7
        def viewEditPayment(request):
        the method redirects the creator who wants to edit the payment value of his event to the edit payment page that retrieves from him the new payment and deadline and then updates it in the event
        Args
        it takes no input however it works by request when the creator clicks on edit payment
        Returns
        it redirects the creator to the edit payment page
        """
    
        return render_to_response("EditPayment.html", locals()) 



def editPayment(request):
        """
        Author: Ola Magdy
        Story: C2-7
        def editPayment(request):
        The method edits the payment amount and the deadline of the event from the event page after the event was launched
        Args
        This method takes no attributes however it uses the POST method to retrieve the new payment amount and deadline
        Returns
        There is no output however it returns the user back to the event page with the edited payment and deadline through render.response
        """
        currentEventId=request.session["eventid"]
        currentEvent = Event.objects.get(pk = currentEventId)
        template=currentEvent.template
        currentComponents= SelectedComponents.objects.filter(template=template)
        for component in currentComponents:
            if component.name =="Payment":
                if request.method == "POST":
                    payAmount = request.POST.get('paymentAmount')
                    deadLine = request.POST.get('deadline')
                    template.payment.paymentAmount = payAmount
                    template.payment.deadline = deadLine
                    template.payment.save()
                    template.save()
                    print " editPayment"
                    print template.payment.paymentAmount
                    print currentEventId
                    currentEvent.template = template
                    currentEvent.save()
                    request.session['event']=currentEvent
                    return viewEvent(request,currentEventId)
                
def assignPayment(request):
    """
    Author: Noreen Fadel
    Story: C4-3
    
        This method allows authorized users to add the payment component to their event. By entering the payment amount and payment deadline date of their event
        The method validates that the user entered thr required data in the correct format
    Args
        There are no attributes for this method
        "POST" method takes from user inputs
        paymentAmount (charfield)
        deadline (charfield)
    Returns
        The method renders to the same page Payment.html
        How to use the function:
        This method is used to retrieve and store payment related information and is later viewed on event's page
        
    """
     
    if request.method == "POST":
        payAmount = request.POST.get('paymentAmount')
        deadLine = request.POST.get('deadline')
        if representsInt(payAmount)!=True:
                invalidPayment = "Please enter a valid payment amount"
                return render_to_response("Payment.html", locals())
        originalPayment = Payment.objects.create(paymentAmount = payAmount, deadline = deadLine) 
        originalPayment.save()
        request.session['Payment']=originalPayment
        return viewAgenda(request)
  



    
def viewEditAgenda(request):
        """
        Author: Ola Magdy
        Story: C2-7
        def viewEditAgenda(request):
        The method redirects the creator who wants to edit the agenda of his event to the edit agenda from the event page after the event was launched
        the method of editing postponed to sprint 2
        Args
        it takes no input however it works by request when the creator clicks on edit agenda
        Returns
        it redirects the creator to the edit agenda page
        """
        return render_to_response("EditAgenda.html", locals())


    
def viewEditLiveStream(request):
    """
    Author: Ola Magdy
    def viewEditLiveStream(request):
        the method redirects the creator who wants to edit the event live stream of his event to the edit live stream page
    Args
    it takes no input however it works by request when the creator clicks on edit live stream
    Returns
    it redirects the creator to the edit live stream page
    """
    return render_to_response("EditLiveStream.html", locals())
 

 

def viewEditSocialMarketing(request):
    """
    Author: Ola Magdy
    Story: C2-7
    def viewEditSocialMarketing(request)
    the method redirects the creator who wants to edit the social marketing of his event to the edit Social Marketing page that retrieves from him the new facebook and twitter URLs and then updates it in the event
    Args
    it takes no input however it works by request when the creator clicks on edit payment
    Returns
    it redirects the creator to the edit social marketing page
    """
    return render_to_response("EditSocialMarketing.html", locals())



def editSocialMarketing(request):
    
    """
    Author: Ola Magdy
    Story: C2-7
    def editSocialMarketing(request):
    The method edits the social marketing of the event from the event page after the event was launched
    it retrieves from the edit Social Marketing html page the new URLs
    the method replaces the old URLs and redirect the creator back
    Args:
    This method takes no attributes however it uses the POST method which retrieves from the user the new URLs
    Returns
    There is no output however it returns the user back to the event page with the edited social marketing component through render.response
    """
    currentEventId = request.session["eventid"]
    currentEvent = Event.objects.get(pk = currentEventId)
    template = currentEvent.template
    currentComponents= SelectedComponents.objects.filter(template=template)
    print currentComponents
    #if currentEvent.creator.email == userEmail: 
    for component in currentComponents:
        if component.name =="Social Marketing":
            if request.method == 'POST':
                facebookUrl = request.POST.get('facebookUrl')
                twitterUrl = request.POST.get('twitterUrl')
                hashTag = request.POST.get('hashTag')
                correctFacebookUrl = "http://www.facebook.com/"
                correctTwitterUrl = "http://twitter.com/"
                if facebookUrl and twitterUrl and hashTag:
                    if facebookUrl[0:24] == correctFacebookUrl and  twitterUrl[0:19]==correctTwitterUrl:
                        userTwitterID = twitterUrl[19:]
                        urlTwitter= correctTwitterUrl + userTwitterID
                        userFacebookID = facebookUrl[24:]
                        urlFacebook= correctFacebookUrl+ userFacebookID
                        template.socialMarketing.facebookUrl = facebookUrl
                        template.socialMarketing.twitterUrl = twitterUrl
                        template.socialMarketing.hashTag = hashTag
                        template.socialMarketing.save()
                        template.save()
                        return viewEvent(request, currentEventId)
                    else:
                        failureMessage = "Please enter the correct Facebook/Twitter Url."
                        return render_to_response("EditSocialMarketing.html", {'failureMessage': failureMessage})
                
                elif facebookUrl and twitterUrl:
                    if facebookUrl[0:24] == correctFacebookUrl and  twitterUrl[0:19]==correctTwitterUrl:
                        userTwitterID = twitterUrl[19:]
                        urlTwitter= correctTwitterUrl+ userTwitterID
                        userFacebookID = facebookUrl[24:]
                        urlFacebook= correctFacebookUrl+ userFacebookID
                        template.socialMarketing.facebookUrl = facebookUrl
                        template.socialMarketing.twitterUrl = twitterUrl
                        template.socialMarketing.save()
                        template.save()
                        return viewEvent(request, currentEventId)
                    else:
                        failureMessage = "Please enter the correct Facebook/Twitter Url."
                        return render_to_response("EditSocialMarketing.html", {'failureMessage': failureMessage})
                
                elif twitterUrl and hashTag:
                    if twitterUrl[0:19]==correctTwitterUrl:
                        userTwitterID = twitterUrl[19:]
                        urlTwitter= correctTwitterUrl+ userTwitterID
                        template.socialMarketing.twitterUrl = twitterUrl
                        template.socialMarketing.hashTag = hashTag
                        template.socialMarketing.save()
                        template.save()
                        return viewEvent(request, currentEventId)
                    else:
                        failureMessage = "Please enter the correct twitter Url."
                        return render_to_response("EditSocialMarketing.html", {'failureMessage': failureMessage})
                
                elif twitterUrl:
                    if twitterUrl[0:19]==correctTwitterUrl:
                        userTwitterID = twitterUrl[19:]
                        urlTwitter= correctTwitterUrl+ userTwitterID
                        template.socialMarketing.twitterUrl = twitterUrl
                        template.socialMarketing.save()
                        template.save()
                        return viewEvent(request, currentEventId)
                    else:
                        failureMessage = "Please enter the correct twitter Url."
                        return render_to_response("EditSocialMarketing.html", {'failureMessage': failureMessage})
                
                elif facebookUrl:
                    if facebookUrl[0:24] == correctFacebookUrl:
                        userFacebookID = facebookUrl[24:]
                        urlFacebook= correctFacebookUrl+ userFacebookID
                        template.socialMarketing.facebookUrl = facebookUrl
                        template.socialMarketing.save()
                        template.save()
                        return viewEvent(request, currentEventId)
                    else: 
                        failureMessage = "Please enter the correct Facebook Url."
                        return render_to_response("EditSocialMarketing.html", {'failureMessage': failureMessage})
                
                elif facebookUrl and hashTag:
                    if facebookUrl[0:24] == correctFacebookUrl:
                        userFacebookID = facebookUrl[24:]
                        urlFacebook= correctFacebookUrl+ userFacebookID
                        template.socialMarketing.facebookUrl = facebookUrl
                        template.socialMarketing.hashTag = hashTag
                        template.socialMarketing.save()
                        template.save()
                        return viewEvent(request, currentEventId)                    
                    else: 
                        failureMessage = "Please enter the correct Facebook Url."
                        return render_to_response("EditSocialMarketing.html", {'failureMessage': failureMessage})
                elif hashTag:
                    template.socialMarketing.hashTag = hashTag
                    template.socialMarketing.save()
                    template.save()
                    return viewEvent(request, currentEventId)                
                elif not facebookUrl and not twitterUrl and not hashTag :
                    failureMessage = "please enter at least one field"
                    return render_to_response("EditSocialMarketing.html", {'failureMessage': failureMessage})

    
def viewEventAfterLaunch(request):
    '''
	Author: Hadeel Mohamed
    viewEventAfterLaunch Documentation
    Story: C2-8
    This method allow creators to view the event page right after create it when they click on launch event button   
    Args: 
    It takes as an argument request from the html through session to take the used template through a session
    Returns:
    The method redirects to CreatorEvent.html page
    How to use the function:
    After the template is created and the components are chosen the required information have been entered for each chosen component
    the creator click on launch event button and CreatorEvent.html appears
    '''
    template = request.session["template"]
    creator = User.objects.get(email=emailSession['email'])
    event=request.session['Event']    
    currentTemplate = event.template
    currentComponents= SelectedComponents.objects.filter(template=currentTemplate)
    request.session["eventid"]=event.id
    for component in currentComponents:
        if component.name =="Location":
            location = Locations.objects.get(event = event)
    template= event.template
    activities = viewEventAgenda(event.id)
    list = List.objects.get(event = event)
    request.session['list'] = list
    items = viewList(list)
    print(activities)
    photoForm = UploadPhoto()
    videoForm = UploadVideo()
    
    user = User.objects.get(email=request.session['email'])
    numberOfLikes=LikeEvent.objects.filter(event=event).count()
    shareNumber=event.countShare
    oldLike = LikeEvent.objects.filter(user=user,event=event)
    return render_to_response("CreatorEvent.html",locals(),context_instance=RequestContext(request))

def viewViewers(request):
    """
    Author: Ahmed Y. Hashad C3-3
    def viewViewers(request)
    This method displays the number of unique visitors of each event
    Arg:
    Event ID and User ID
    Returns:
    Number of unique visits of an event
    How it works:
    When the user accesses the event page this method checks if this user have viewed the event before and if yes it does nothing else it adds him/her to the list of viewers and displays the new number of unique viewers
    """
    eventID = request.session["eventid"]
    userID = request.session["email"]
    event = Event.objects.get(pk = eventID)
    user = User.objects.get(email = userID)
    viewedUsers = PageViewers.objects.filter(event = event)
    flag = False
    for viewd  in viewedUsers:
        if flag == False:
            if viewd.user.email == userID:
                flag = True    
    if flag == False:
        PageViewers.objects.create(user = user, event = event)
        addOne = viewedUsers.count() + 1
    else:
        addOne = viewedUsers.count() 
    return addOne

def viewCounter(request,id):
    """
	Author: Ahmed Y. Hashad C3-3
	def viewCounter(request,id):
	This method displays the number of views for a certain event . It increments this number if the user is not the event creator. 
	Arg:
	id (Integer) : the event's autogenerated ID
	Return:
	It returns the number of views of a certain event.
	How it works:
	The user accesses the event page which will display the number of views.
	"""
    eventID = id
    event = Event.objects.get(pk = eventID)
    page = PageCounter.objects.get(event = event)
    username = request.session['email']
    if event.creator.email == username:
        return page.pageCounter
    else:
        page.pageCounter = page.pageCounter + 1
        pageCount = page.pageCounter
        page.save()
        return pageCount   
    
def viewEvent(request , eventId):
    '''
	Author: Hadeel Moahmed
	viewEvent Documentation
    Story: C2-8
    This method allow both creators and users to view the event page 
    but both see it in different views and different Htmls pages.
    Args: 
    It takes an argument request from the html page to 
    takes the user email through session in case if it is a creator 
    or to get the eventId and it sets it to the event 
    I am viewing and it also takes as an argument the eventId as users depend on it. 
    Returns:
    The method redirects to two different HTML pages based on 
    whether the person is a creator or a user of the event 
    and both HTML pages shows the event page requested 
    How to use the function:
    It checks if the person who wants to view the event if it is a creator or user and 
    it checks that through the userEmail that it takes through a session 
    if it is equal to the creators email it returns CreatorEvent.html 
    while if it is a user it just sets the eventId to the event I am viewing 
    and redirects him/her to UserEvent.html 

    '''
    flag = "False"
    userEmail = request.session['email']
    event = Event.objects.get(pk = eventId)
    moderator = EventModerator.objects.filter(event = event)
    request.session["eventid"] = eventId
    currentComponents= SelectedComponents.objects.filter(template=event.template)
    for component in currentComponents:
        if component.name =="Location":
            location = Locations.objects.get(event = event)
    attending = viewAttend(request)
    maybeAttending = viewMaybe(request)
    notAttending = viewNotAttending(request)
    payedAttendees = viewPayedAttendees(request)
    getUser = User.objects.get(email = userEmail)
    
    photoForm = UploadPhoto()
    videoForm = UploadVideo()
    
    if event.isPublic!=True:
        for i in Invited.objects.all():
            if i.user==getUser and i.event==event:
                inviter = event.creator.first_name + " " + event.creator.last_name +" invited you"
                flag= "True"
                break
    if event.isPublic!=True:
        if flag=="False":
            notAuthorizedToRespond = "You are not authorized to respond to this event"
    for a in Attending.objects.all():
        if a.user==getUser and a.event==event:
            attendingEventResponse = "You are attending this event" 
            break
    for m in MaybeAttending.objects.all():
        if m.user==getUser and m.event==event:
            maybeAttendingEventResponse = "You are maybe attending this event"
            break
    for n in NotAttending.objects.all():
        if n.user==getUser and n.event==event:
            notAttendingEventResponse = "You are not attending this event"
            break
    
    if event.creator.email == userEmail:
            user = User.objects.get(email=userEmail)
            numberOfLikes=LikeEvent.objects.filter(event=event).count()
            shareNumber=event.countShare
            oldLike = LikeEvent.objects.filter(user=user,event=event)
            
            template= event.template
            viewerCount = viewViewers(request)
            pageCounter = viewCounter(request,eventId)
            activities = viewEventAgenda(eventId)
            list = List.objects.get(event = event)
            request.session['list'] = list
            print list.title
            items = viewList(list)
            completedTasks = viewListProgress(list)  
            notCompletedTasks = 100- completedTasks
            credit = viewCurrentCredit(eventId)
            event = Event.objects.get(pk = eventId)
            page = Page.objects.filter(event = event)
            links = Link.objects.filter(event = event)

            return render_to_response("CreatorEvent.html",locals(),context_instance=RequestContext(request))
    elif moderator:
            currentTemplate = event.template
            currentComponents= SelectedComponents.objects.filter(template=currentTemplate)
            user = User.objects.get(email=userEmail)
            numberOfLikes=LikeEvent.objects.filter(event=event).count()
            shareNumber=event.countShare
            oldLike = LikeEvent.objects.filter(user=user,event=event)
            template= event.template
            viewerCount = viewViewers(request)
            pageCounter = viewCounter(request,eventId)
            activities = viewEventAgenda(eventId)
            list = List.objects.get(event = event)
            items = viewAssignedTasks(list , userEmail)
            request.session["list"] = list
            #alreadyAssigned = request.session["alreadyAssigned"]

            completedTasks = viewListProgress(list)  
            notCompletedTasks = 100- completedTasks
            credit = viewCurrentCredit(eventId)
            return render_to_response("ModeratorEvent.html",locals(),context_instance=RequestContext(request))

                
    else : 
            user = User.objects.get(email=userEmail)
            numberOfLikes=LikeEvent.objects.filter(event=event).count()
            shareNumber=event.countShare
            oldLike = LikeEvent.objects.filter(user=user,event=event)
            
            event=Event.objects.get(pk = eventId)
            template= event.template
            activities = viewEventAgenda(eventId)
            viewerCount = viewViewers(request)
            pageCounter = viewCounter(request,eventId)
            return render_to_response("UserEvent.html",locals(),context_instance=RequestContext(request))
        




               
def createPage(request):
    """
	def createPage(request):
	Author : Inas Khodeir
	Story : C5-16
	this method redirects to the page where the event creator creats static pages
	Args : no args
	Returns: 
	the redirect to the createPage.html
	How to use the function:
	Type the localhost "localhost:8000/CreatePage/" 
	"""
    return render_to_response("CreatePage.html",RequestContext(request))

def createRequest (request):
    """
	def createRequest(request):
	Author : Inas Khodeir
	Story : C5-16
	this method redirects to the page where the event creator could create a menu or page
	arguments : no arguments
	Returns: 
	the redirect to the Create.html
	How to use the function:
	Type the localhost "localhost:8000/Create/"     
   """
    return render_to_response("Create.html",RequestContext(request))


def viewUnchosenComponents(request):
    """
    Author: Sherine Nouh
    Story: C2-15
    This method checks the components that were not chosen by the creator during the creation process, then displays a button for every unchosen component under the add page button on the event page
    Args:
    The method takes not input 
    Returns:
    The method has no returns however it displays the page of the component chosen to be added for the creator to fill the required information        
    How the function works:
    The method is called upon clicking on add page button on the event page
    http://127.0.0.1:8000/CreatePage/
    """

    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
    template = currentEvent.template
    currentComponents = SelectedComponents.objects.filter(template=template)
    for item in currentComponents:
        if item.name=="Location":
            isLocation="true"  
        if item.name=="Payment":
            isPayment="true"
        if item.name=="Agenda":
            isAgenda="true"  
        if item.name=="Media":
            isMedia="true" 
        if item.name=="Social Marketing":
            isSocialMarketing="true"  
        if item.name=="Live Stream":
            isLiveStream="true" 
    return render_to_response("CreatePage.html",locals(), RequestContext(request))    

def addUnchosenComponents(request):
    """
    Author: Sherine Nouh
    Story: C2-15
    This method checks the component of the button that has been clicked, then redirects the creator to the page of this component in order to create it
    Args:
    The method takes not input however it uses a post method to determine the button of which component has been checked to be added
    Returns:
    The method has no returns however it redirects the creator to the page of this component in order to create it   
    How the function works:
    The method is called upon clicking on the button of adding a new component
    http://127.0.0.1:8000/addUnchosenComponents/
    """
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
    template = currentEvent.template
    currentComponents = SelectedComponents.objects.filter(template=template)
    newChoices = NewChoices.objects.filter(template=template)
    
    if request.method=="POST":
        print(request.POST.get('name'))
        if request.POST.get('name')=="Add Live Stream":
            NewChoices.objects.create(name="Live Stream", template=template)
#            newChoices=request.session['newChoices']
#            newChoices.append("Live Stream")
#            request.session['newChoices']=newChoices
            SelectedComponents.objects.create(name="Live Stream",template=template)
            return render_to_response("LiveStream.html",locals(),RequestContext(request))
        if request.POST.get('name')=="Add Payment":
            NewChoices.objects.create(name="Payment", template=template)
#            newChoices=request.session['newChoices']
#            newChoices.append("Payment")
#            request.session['newChoices']=newChoices
            SelectedComponents.objects.create(name="Payment",template=template)
            return render_to_response("Payment.html",locals(),RequestContext(request))
        if request.POST.get('name')=="Add Agenda":
            NewChoices.objects.create(name="Agenda", template=template)
#            newChoices=request.session['newChoices']
#            newChoices.append("Agenda")
#            request.session['newChoices']=newChoices
            SelectedComponents.objects.create(name="Agenda",template=template)
            return render_to_response("Agenda.html",locals(),RequestContext(request))
        if request.POST.get('name')=="Add Social Marketing":
            NewChoices.objects.create(name="Social Marketing", template=template)
#            newChoices=request.session['newChoices']
#            newChoices.append("Social Marketing")
#            request.session['newChoices']=newChoices
            SelectedComponents.objects.create(name="Social Marketing",template=template)
            return render_to_response("Social.html",locals(),RequestContext(request))
        if request.POST.get('name')=="Add location":
            NewChoices.objects.create(name="Location", template=template)
#            newChoices=request.session['newChoices']
#            newChoices.append("Location")
#            request.session['newChoices']=newChoices
            SelectedComponents.objects.create(name="Location",template=template)
            return render_to_response("CLocation.html",locals(),RequestContext(request))
        if request.POST.get('name')=="Add Media":
            NewChoices.objects.create(name="Media", template=template)
#            newChoices=request.session['newChoices']
#            newChoices.append("Media")
#            request.session['newChoices']=newChoices
            SelectedComponents.objects.create(name="Media",template=template)
            return render_to_response("Media.html",locals(),RequestContext(request))

         

        
                        

	
	
	
   
def addCMS(request):
    """
    def addCMS(request):
    Author : Inas Khodeir
    Story : C5-16

    this method takes the attributes of the page and create a page for the event creator then redirects the event creator to the event page
    Args : no args
    Returns: 
    it returns the pages
    How to use the function:
    Type the localhost "localhost:8000/CreatePage/"     
    """   
    if request.method == "POST":
        title = request.POST.get('title', '')
        description = request.POST.get('description','')
        category = request.POST.get('Category','')
        eID = request.session["eventid"]
        event = Event.objects.get(pk = eID)
        newCategory = Category.objects.create(categoryTitle = category)
        newPage = Page.objects.create(title=title, description = description, category = newCategory,event_id=event.id)
        pageID = newPage.id
        request.session['pageID'] = newPage.id
        return checkEvents(request)
    else: 
        return viewUnchosenComponents(request)

def deleteCMS(request):
    """
    def deleteCMS(request):
    Author : Inas Khodeir
    Story : C5-20
    this method deletes the page created by the event creator
    Args : no args
    Returns: 
    it returns the pages
    How to use the function:
    Type the localhost "localhost:8000/viewCMSPage/"     
    """  
    pageid = request.session['pageID']
    Page.objects.get(pk = pageid ).delete()
    return checkEvents(request)
def editCMS(request):
    """
    def editCMS(request):
    Author : Inas Khodeir
    Story : C5-20
    this method edits the page created by the event creator
    Args : no args
    Returns: 
    it returns the pages edited by the event creator
    How to use the function:
    Type the localhost "localhost:8000/editCMS/"     
    """ 
    if request.method == 'POST':    
        pageid = request.session['pageID']
        pages = Page.objects.get(pk=pageid)
        newDescription = request.POST.get('description','')
        pages.description = newDescription
        pages.save()
        
        
        
        return checkEvents(request)        
def createMenus(request):
    """
    def createMenus(request):
    Author : Inas Khodeir
    Story : C5-16
    this method takes the attributes of the menu and create a menu for the event creator then redirects the event creator to the event page
    Args : no arguments
    Returns: 
    it returns to the event page
    How to use the function:
    Type the localhost "localhost:8000/CreateMenu/" 
    """
    if request.method == "POST":
        title = request.POST.get('title', '')
        if title:
            eID = request.session["eventid"]
            
            event = Event.objects.get(pk = eID)
            
            newMenu = Menu.objects.create(title=title,event_id=event.id )
            newMenu.save()
            request.session['nMenu']= newMenu
            return render_to_response("menus.html",locals())
        else:
            Error = "Please enter a title"
            return render_to_response("createMenu.html", locals())
    else:
        return render_to_response("CreateMenu.html", RequestContext(request))


def addLink(request):
    """
    def addLink(request):
    Author : Inas Khodeir
    Story : C5-16
    this method takes the attributes of the link and create a link in a menu for the event creator then redirects the event creator to the event page
    Args : no args
    Returns: 
    it returns to the event page
    How to use the function:
    Type the localhost "localhost:8000/Menus/" 
    """
    if request.method=="POST":
        title = request.POST.get('link')
        name = request.POST.get('lname')
        if title:
            eID = request.session["eventid"]
            
            event = Event.objects.get(pk = eID)
            newMenu = request.session['nMenu']
            newLink = Link.objects.create(url = title, name = name, menu = newMenu, event_id = event.id)
            
            linkID = newLink.id
            request.session['linkID'] = newLink.id
            newLink.save()
            
            links=Link.objects.filter(menu=newMenu)
            
            
            return render_to_response("menus.html",locals())
        else:
            Error = "Please enter a title"
            return render_to_response("menus.html", locals())
      
    return HttpResponse("hfhfh")
def deleteMenu(request):
    """
    def deleteMenu(request):
    Author : Inas Khodeir
    Story : C5-20
    this method deletes the menu created by the event creator
    Args : no args
    Returns: 
    it returns the pages
    How to use the function:
    Type the localhost "localhost:8000/viewMenus/"     
    """   
    
    menuid = request.session['nMenu'].id
    
    Menu.objects.get(pk = menuid ).delete()
    return checkEvents(request)
    
def editMenu(request):
    """
    def editMenu(request):
    Author : Inas Khodeir
    Story : C5-20
    this method edits the menu created by the event creator
    Args : no args
    Returns: 
    it returns the pages edited by the event creator
    How to use the function:
    Type the localhost "localhost:8000/editMenu/"     
    """

    if request.method == 'POST':    
        linkid = request.session['linkID']

        links = Link.objects.get(pk=linkid)
        newURL = request.POST.get('link','')
        links.url = newURL
        links.save()

        
        return checkEvents(request)

def checkEvents(request):
    """    
    def checkEvents(request):
    Author: Inas Khodeir
    Story: C5-16
    this method views all the created pages, menus and categories
    Args : no args
    Returns: 
    it returns to the event page
    How to use the function:
    Type the localhost "localhost:8000/EventsTest/" 
    """
    page = Page.objects.all()
    links = Link.objects.all()
    categories = Category.objects.all()
    eID = request.session["eventid"]
    
    return viewEvent(request, eID)

def showPages (request,id):
    """
    def showPages(request):
    Author: Inas Khodeir
    Story: C5-16
    this method views the created page of the user with its content
    Args : no args
    Returns: 
    it returns the page the creator created
    How to use the function:
    Type the localhost "localhost:8000/ViewCMSPage/" 
    """
    page = Page.objects.get(pk = id)
    return render_to_response('ViewCMSPage.html',locals())

def viewPage(request):
    """    
    def viewPage(request):
    Author: Inas Khodeir
    Story: C5-16
    this method redirects the user to a page where he can choose to add a page or a menu
    Args : no args
    Returns: 
    it returns a page havingc two buttons add Page and add Menu
    How to use the function:
    Type the localhost "localhost:8000/EventsTest/" 
    """
    if request.method == "POST":
        return render_to_response("EventsTest.html")


def showMenus (request,id):
    """
    def showMenus(request):
    Author: Inas Khodeir
    Story: C5-16
    Args : no args
    this method views the created menu of the user with its content
    Returns: 
    it returns the menu the creator created
    How to use the function:
    Type the localhost "localhost:8000/Menus/" 
    """ 
   
    links = Link.objects.get(pk = id)
    return render_to_response('viewMenus.html',locals())
    
  

def addPayedAttendees(request):
    userEmail = request.session['email']
    print(userEmail)
    user=User.objects.get(email=userEmail)
    eventId=request.session['eventid']
    event=Event.objects.get(pk=eventId)
    #u = User.objects.create(email = userEmail)
   # eventId = request.POST.get ('EventID' , '')
  #  event = Event.objects.create( eventID =  '2' ,  creator = u)
#    for e in Event.objects.all():
       # if e.EventID == eventID:
    payment="false"   
    for a in PayedAttendees.objects.all():
        print("innnn")
        if a.user.email==userEmail:
            if a.event==event:
                payment="true"
                successmsg = "You have already paid"
                return render_to_response("AttendeePayment.html",locals())
    PayedAttendees.objects.create(user = user, event= event ) 
    successmsg = "You have successfully paid for the event =)." 
    return render_to_response("AttendeePayment.html", locals())
'''addPayedAttendees Documentation 
this method enables the attendees to pay for the events they are attending
Args: no inputs , it takes only a request from the pay 
Returns:
this method create a new payed Attendee and insert it in the data base
How to use the function:
the user use it when they press on the button pay in the event page'''
       
def startPayment (request):
    return render_to_response ("AttendeePayment.html")
'''startPayment Documentation
this method redirect to the payment HTML
Args: no inputs
Returns:
redirect to the payment HTML
How to use the function:
the user use it when they press on button pay in the eventPage'''


def viewPhotos(request):
    """
    Author: Aya Raafat
    
    Story: C4-10
    
        this method redirects to a page where the event photos are displayed
    Args:
        There are no attributes given for the method itself
    Return:
        it redirects to photos.html where the photos are displayed
    How the function works:
        the method is called upon clicking on the photos link displayed on the event page 
        which redirects to the page where the event photos are displayed     
    """
    eventId = request.session['eventid']
    event = Event.objects.get(pk = eventId)
    images = Photo.objects.filter(event = event)
    return render_to_response ('Photos.html', locals())



def uploadPhoto(request):   
    """
    Author: Aya Raafat
    
    Story: C4-10
    
        this method enables the user to upload photos while creating new event and view them on their event pages 
    Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST"
    Return:
        it calls the method viewMedia which views the uploaded photos 
    How the function works:
        the method is called upon clicking on the upload button in the media template
        and browse the desired photos from their source and click upload which then view
		the photos on the event page      
    """
    try:
        if request.method == 'POST':
    
            form = UploadPhoto(request.POST, request.FILES)
            files = request.FILES['fileImage']
            eventId = request.session["eventid"]
            event = Event.objects.get(pk = eventId)
            photo = Photo.objects.create(fileImage = files, event = event )
            photo.save()
            return viewMedia(request)
        else:
            photoForm = UploadPhoto()
            videoForm = UploadVideo()
            return render_to_response('Media.html', locals())
    except:
        errorMsg = "You haven't chosen a photo to be uploaded"
        photoForm = UploadPhoto()
        videoForm = UploadVideo()
        return render_to_response('Media.html', locals())

    
def uploadMorePhotos(request):   
    """
    Author: Aya Raafat
    
    Story: C4-10
    
        this method enables the user to upload more photos after creating the event and view them on their event pages 
    Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST"
    Return:
        it calls the method viewMedia which views the uploaded photos 
    How the function works:
        the method is called upon clicking on the upload more photos button in the event page
        and browse the desired photos from their source and click upload which then view the images on
        the event page      
    """
  
    

    try:
        if request.method == 'POST':
    
            form = UploadPhoto(request.POST, request.FILES)
            files = request.FILES['fileImage']
            eventId = request.session["eventid"]
            event = Event.objects.get(pk = eventId)
            photo = Photo.objects.create(fileImage = files, event = event )
            photo.save()
            return viewPhotos(request)
    except:
        eventId = request.session["eventid"]
        errorMsg = "You haven't chosen a photo to be uploaded"
        photoForm = UploadPhoto()
        return viewEvent(request, eventId)

def viewVideos(request):
    """
        def viewVideos(request):
		Author: Noreen Fadel
        Story:  C4-9
        This method redirects to the events page where the videos will be displayed
        Args:
        There are no attributes for this method
        Returns:
        It redirects to videos.html
        How to use the function:
		This method is used when on the event page a button with video link is displayed which redirects to the page where the events videos are displayed	
        """

    eventId = request.session['eventid']
    event = Event.objects.get(pk = eventId)
    videos = Video.objects.filter(event = event)
    return render_to_response ('Videos.html', locals())

def uploadVideo (request):
    """
    def uploadVideo(request):
	Author: Noreen Fadel
    Story:  C4-9
    This method enables users to upload videos during the creation of any event 
    Args:
    There are no attributes for this method
    "POST" method takes from user inputs
    Returns:
    This method calls viewMedia which views uploaded videos
    How to use the function:
	This method is used when clicked upon the upload button in media template and user gets to choose which video to upload and then will be able to view them on event pag
	"""
    try:
        if request.method == 'POST':
            form = UploadVideo(request.POST, request.FILES)    
            files = request.FILES['video']
            title = request.POST.get('title', '')
            eventId = request.session["eventid"]
            event = Event.objects.get(pk = eventId)
            video = Video.objects.create(title = title, video = files, event = event)
            video.save()
            return viewMedia(request)
        else:
            photoForm = UploadPhoto()
            videoForm = UploadVideo()
            return render_to_response('Media.html', locals())
    except:
        errorMsg = "You haven't chosen a video to be uploaded"
        photoForm = UploadPhoto()
        videoForm = UploadVideo()
        return render_to_response('Media.html', locals())


def uploadMoreVideos(request):
    """
        Author: Noreen Fadel
        Story:  C4-9
        This method enables users to upload more videos after the events creation and then view them on the events page
        Args:
        There are no attributes for this method
         "POST" method takes from user inputs
        Returns:
        This method calls viewMedia which views uploaded videos
        How to use the function:
		This method is retrieved when the button upload more videos is clicked upon in the events page and then the user is able to upload whichever selected video
	
	"""
    try:
        if request.method == 'POST':
            form = UploadVideo(request.POST, request.FILES)    
            files = request.FILES['video']
            title = request.POST.get('videoName', '')
            eventId = request.session["eventid"]
            event = Event.objects.get(pk = eventId)
            video = Video.objects.create(title = title, video = files, event = event)
            video.save()
            return viewVideos(request)
    except:
        eventId = request.session["eventid"]
        errorMsg = "You haven't chosen a video to be uploaded"
        videoForm = UploadVideo()
        return viewEvent(request, eventId)

    

            
def shareEvent(request,eventId):
    """Author : Dalia Hegazy C4-14
    This method send e-mails to the users that did not know about the event before and incrementing the number of shares by one But if user is not logged in he will be automatically redirected to login page
    Args:
         This method takes the request coming for the page and the eventId that represents the id of a specific event
    Returns:  
         This method returns Html page that contains the share and the like buttons and the number of shares and likes done for specific event
    How to use the function:
        Type the localhost "127.0.0.1:8000/EventPage/1/share/" in the URL where one is the eventId"""
    if 'email' not in request.session:
        return HttpResponseRedirect('/homePage/')
    if request.session['email'] == "":
        return HttpResponseRedirect('/homePage/')
    
    if request.method== "POST":
        attendingUser = Attending.objects.filter(event=eventId)
        maybeAttendingUser =  MaybeAttending.objects.filter(event=eventId)
        notAttendingUser = NotAttending.objects.filter(event=eventId)
        notInvitedUser=User.objects.all() 
        for temp in attendingUser: 
            notInvitedUser=notInvitedUser.exclude(id=temp.user_id)
        for temp in maybeAttendingUser: 
            notInvitedUser=notInvitedUser.exclude(id=temp.user_id)
        for temp in notAttendingUser: 
            notInvitedUser=notInvitedUser.exclude(id=temp.user_id)
        event=Event.objects.get(id=eventId) 
        event.countShare = event.countShare+1
        event.save()
        
        for u in notInvitedUser:
            send_mail('Eventati', 'Dear '+u.first_name+' \n This Event Has Been Shared\n The link for the event : http://localhost:8000/ResultsEvents/'+eventId+'/', 
                      'eventati.noreply@gmail.com',[u.email], False,'eventati.noreply','Eventati2012');
        return HttpResponseRedirect('/EventPage/'+eventId)




    
def likeEvent(request,eventId,userId):
    """Author : Dalia Hegazy C4-15
    This method add to the database the userId and eventId to the LikeEvent table if the user wants to like this event and he isn't already liked it but if he already liked this event he will unlike it But if user is not logged in he will be automatically redirected to login page
    Args:
         This method takes the request coming from the page , the eventId that represents the id of a specific event and the userId represents the id of a specific user
    Returns:  
         This method returns Html page that contains the share and the like buttons and the number of shares and likes done for specific event
    How to use the function:
         Type the localhost "127.0.0.1:8000/EventPage/1/like/2/" in the URL where one is the eventId ,where 2 is the userId"""
    if 'email' not in request.session:
        return HttpResponseRedirect('/homePage/')
    if request.session['email'] == "":
        return HttpResponseRedirect('/homePage/')
    
    if request.method== "POST":
        oldLike = LikeEvent.objects.filter(user=userId,event=eventId)
        if oldLike.count() == 0:
            like = LikeEvent(user_id=userId, event_id=eventId)
            like.save()
            return HttpResponseRedirect('/EventPage/'+eventId)
        else :
            oldLike.delete()
            return HttpResponseRedirect('/EventPage/'+eventId)



def viewEventAgenda(id):
    
    """
        def viewEventAgenda(id):
        Author : Reem Tarek C3-1
        This method retrieves all the activities of an agenda related to a certain event according to its ID on the event page.
        Args:
        Id (int) : the event's autogenerated ID.
        Returns:
        The method returns a list of activities related to the agenda of the event the user wants to see.
        How to use this function:
        The user will access the event page where the agenda will be displayed.
    """
    event = Event.objects.get(pk = id)
    agenda = event.template.agenda
    activities = Activity.objects.filter(agendaID = agenda)
    return activities



def deleteTask(request):
    
    """
        def deleteTask(request):
        Author : Reem Tarek C3-11
        This method allows the event creator to edit the Task list by deleting items.
        Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST" which takes from the user:
        list : A list of checked boxes indicating the items or tasks the event creator wants to delete
        Returns:
        It calls the method viewEvent(request , id) that displays the updated event information.
        How to use this function:
        The event creator will access the event page, then checks the items he/she wants to delete and then clicking delete button
    """
    if request.method =='POST':
        itemsList = request.POST.getlist('task')
        list = request.session['list']
        for item in itemsList:
                Item.objects.get(pk = item , todoList = list ).delete()
    eventID = request.session["eventid"]
    return viewEvent(request , eventID)



def completeTask(request):
    """
	Author: Ahmed Y. Hashad C3-10
	def completeTask(request):
	This method enables the event creator to strikrthrough completed task by changing their font style to Strikethrough and saves them.
    Args:
	No defined Arguments. However, this method is initiated through "POST" which takes from the user a list of checkboxes.
	Returns :
	updated task list with completed task strikethroughed
	How to use this function:
	The creator accesses the event page in which he will select item/tasks that he wants to complete and submit the complete button.
    """
    if request.method =='POST':
        itemsList = request.POST.getlist('task')
        list = request.session['list']
        for itemX in itemsList:
            item = Item.objects.get(pk = itemX , todoList = list )
            item.completed = True
            item.save()
    eventID = request.session["eventid"]            
    return viewEvent(request , eventID)

def viewList(list):
    
    """
        def viewList(list):
        Author : Reem Tarek C3-8
        This method retrieves all the items/tasks of a Task list of a certain event on the event page.
        Args:
        list (List) : the task list of a certain event.
        Returns:
        The method returns a list of items/tasks related to the Task list of the event the event creator wants to see.
        How to use this function:
        The event creator will access the event page where the Task list  will be displayed.
    """
    items = Item.objects.filter(todoList = list)
    return items


def createAnAgenda (request):
    """
    def createAnAgenda(request):
    Author: Sarah Hesham
    Story:c3-6
    This method enables the event creator to create add the Agenda Component to their event page.
    Args:
        There are no attributes given for the method itself 
        However this method is initiated through "POST" which takes from the user:
            title (charField)
    Returns:
        If the user enters a title for the agenda, this method returns the user to the updated Agenda.html where the user will find a table to start adding activities for their agenda. Else the user is redirected to another "failed" page.
    How to use the function:
        The user creates an event and select the Agenda Component
    """   
    if request.method=="POST":
        title = request.POST.get('title' , '')
        agenda =  Agenda()
        agenda.title = title
        agenda.save()
        request.session['agenda'] = agenda          
        creation = "True"
        return render_to_response("Agenda.html", locals()) 
     
     
def refreshAgenda (request):
    """    
    def refreshAgenda(request):
    Author: Sarah Hesham
    Story:c3-6
    This method is called as the user creates activities so as to update the table and display the latest updates of the agenda.
    Args:
        There are no attributes for the method  
    Returns:
        redirects the user to the updated Agenda.html where the user views updated agenda
    How to use the function:
        This method is called and used as the user starts adding new activities so as to update the agenda.
    """
    creation = "True"
    agenda =  request.session['agenda'] 
    Activities = Activity.objects.filter(agendaID = agenda)
    template = request.session["template"]
    return render_to_response("Agenda.html" , locals())



def createActivity(request):
    """
    def CreateActivity(request):
    Author: Sarah Hesham 
    Story:c3-6
    In order to create an agenda for a certain event, the event creator has to add activities. So basically this method retrieves from the user the attributes related to creation of an activity
    Args:
        There are no attributes given for the method itself 
        However this method is initiated through "POST" which takes from the user:
            Description (text) : title of the activity
            Start Time (timeField) : activity start time
            End Time (timeField) : activity end time
    Returns:
        This method redirects the event creator to Agenda.html so as to display the new activities created and allow the user to add more activities.
    How to use the function:
        The user will create an event and select the Agenda component, and after creating an agenda the user will start adding activities. 
    """   
    creation = "True"
    agenda =  request.session['agenda'] 
    template = request.session["template"]
    Activities = Activity.objects.filter(agendaID = agenda)
    if request.method=='POST':
        text = request.POST.get('textID' , '')
        start = request.POST.get('StartTime' , '')
        end = request.POST.get('EndTime' , '')
        template = request.session["template"]
        agendaSession = request.session['agenda']
        print start
        print end
        newActivity = Activity()
        newActivity.description = text
        newActivity.startTime = start
        newActivity.endTime = end
        newActivity.agendaID = agendaSession
        newActivity.save()
        return  refreshAgenda(request)


         
          
def deleteActivity(request):
    """
        def deleteActivity(request)
        Author : Sarah Hesham 
        Story :C3-19
        This method allows the event creator to delete activities while creating the agenda of their event.
        Args:
            There are no attributes given for the method itself
            However this method is initiated through "POST" which takes from the user:
                selectedActivity : A list of checked boxes indicating the activities the event creator wants to delete
        Returns:
            It calls the method refreshAgenda(request) that displays the updated Agenda.
        How to use this function:
            The event creator will start creating an Event, and while creating the agenda, he/she clicks delete button to delete an activity in the Agenda
    """
    if request.method =='POST':
        selectedActivity = request.POST.get('delete')
        agenda = request.session['agenda']
        Activity.objects.filter(pk = selectedActivity , agendaID = agenda).delete()
    return refreshAgenda(request)
    
    
def isTimeFormat(startTime,endTime):    
    """    
    def isTimeFormat(startTime,endTime):
    Author: Sarah Hesham
    Story:c3-6
    This method is called as the user creates activities so as to ensure the user enters the time in the right format.
    Args:
        startTime : the activity or event's start time
        endTime : the activity or event's end time      
    Returns:
        returns a boolean statement with whether or not the time format is in the right format 
    How to use the function:
        This method is called as the user starts adding new activities.
    """   
    try:
        if time.strptime(startTime, '%H:%M') and time.strptime(endTime, '%H:%M'):
            return True
    except ValueError:
            return False
            
def editActivity(request):
    """
        def editActivity(request)
        Author : Sarah Hesham 
        Story :C3-6
        This method allows the event creator to edit activities while creating event's agenda.
        Args:
            There are no attributes given for the method itself
            However this method is initiated through "POST" which takes from the user:
                selectedActivity : A list of checked boxes indicating the activities the event creator wants to edit
                Description (text) : title of the activity
                Start Time (timeField) : activity start time
                End Time (timeField) : activity end time
        Returns:
            It calls the method editRefreshAgenda(request) that displays the updated Agenda.
        How to use this function:
            The user will create an event and select the Agenda component, and after creating an agenda the user will start editing activities. 
    """   
    creation="True"
    template = request.session["template"]
    agenda =  request.session['agenda']   
    Activities = Activity.objects.filter(agendaID = agenda)
    if request.method =='POST':
        selectedActivity = request.POST.get('activity')
        text = request.POST.get('textID' , '')
        start = request.POST.get('StartTime' , '')
        end = request.POST.get('EndTime' , '')
        agenda = request.session['agenda']
        newActivity = Activity.objects.get(pk =selectedActivity, agendaID = agenda)
        newActivity.description = text
        newActivity.startTime = start
        newActivity.endTime = end
        newActivity.save()
        return  refreshAgenda(request)


def removeLocation(request):
    """
    removeLocation Documentation
    Author: Mayada Al-Sawah C2-5
    This method enables the user to remove the Location component after its been added to the event page.
    Args:
        No arguments taken.
    Returns:
            Redirected to a page saying that this component has been removed
    How to use the function:
            Open http://127.0.0.1:8000/viewEventAfterLaunch/ then click Remove Location"
    """
    
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
#   currentEvent = Event.objects.get(pk=81)
    template = currentEvent.template
    print currentEvent.template.eventName
    currentComponents = SelectedComponents.objects.filter(template=template)

    if request.method == "POST":
        for item in currentComponents:
            if item.name=="Location":
                location = Locations.objects.get(event = currentEvent)
                location.delete()
                SelectedComponents.objects.filter(template=template,name="Location").delete()
                print(SelectedComponents.objects.filter(template=template,name="Location"))
                return viewEvent(request,currentEventId)
  
                               
def removePayment(request):
    """
	removePayment Documentation
	Author: Mayada Al-Sawah C2-5
    This method enables the user to remove the Payment component after its been added to the event page.
    Args:
	    No arguments taken.
    Returns:
			Redirected to a page saying that this component has been removed
    How to use the function:
			Open http://127.0.0.1:8000/viewEventAfterLaunch/ then click Remove Payment"
	""" 
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
 #  currentEvent = Event.objects.get(pk=81)
    template = currentEvent.template
    print currentEvent.template.eventName
    currentComponents = SelectedComponents.objects.filter(template=template)

    if request.method == "POST":
        for item in currentComponents:
            if item.name=="Payment":
                SelectedComponents.objects.filter(template=template,name="Payment").delete()
                print(SelectedComponents.objects.filter(template=template,name="Payment"))
                return viewEvent(request,currentEventId)

                
def removeMedia(request):
    """
	removeMedia Documentation
	Author: Mayada Al-Sawah C2-5
    This method enables the user to remove the Media component after its been added to the event page.
    Args:
		No arguments taken.
    Returns:
			Redirected to a page saying that this component has been removed
    How to use the function:
			Open http://127.0.0.1:8000/viewEventAfterLaunch/ then click Remove Media"
	""" 
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
 #   currentEvent = Event.objects.get(pk=81)
    template = currentEvent.template
    print currentEvent.template.eventName
    currentComponents = SelectedComponents.objects.filter(template=template)


    if request.method == "POST":
        for item in currentComponents:
            if item.name=="Media":
                SelectedComponents.objects.filter(template=template,name="Media").delete()
                print(SelectedComponents.objects.filter(template=template,name="Media"))
                return viewEvent(request,currentEventId)

                           
                           
def removeAgenda(request):
    """
	removeAgenda Documentation
	Author: Mayada Al-Sawah C2-5
	This method enables the user to remove the Agenda component after its been added to the event page.
    Args:
        No arguments taken.
    Returns:
			Redirected to a page saying that this component has been removed
    How to use the function:
			Open http://127.0.0.1:8000/viewEventAfterLaunch/ then click Remove Agenda"
	""" 
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
 #   currentEvent = Event.objects.get(pk=81)
    template = currentEvent.template
    print currentEvent.template.eventName
    currentComponents = SelectedComponents.objects.filter(template=template)


    if request.method == "POST":
        for item in currentComponents:
            if item.name=="Agenda":
                SelectedComponents.objects.filter(template=template,name="Agenda").delete()
                print(SelectedComponents.objects.filter(template=template,name="Agenda"))
                return viewEvent(request,currentEventId)

 
def removeSocialMarketing(request):
    """
	removeSocialMarketing Documentation
	Author: Mayada Al-Sawah C2-5
    This method enables the user to remove the Social Marketing component after its been added to the event page.
    Args:
        No arguments taken.
    Returns:
			Redirected to a page saying that this component has been removed
    How to use the function:
			Open http://127.0.0.1:8000/viewEventAfterLaunch/ then click Remove Social Marketing"
	""" 
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
#   currentEvent = Event.objects.get(pk=81)
    template = currentEvent.template
    print currentEvent.template.eventName
    currentComponents = SelectedComponents.objects.filter(template=template)

    if request.method == "POST":
        for item in currentComponents:
            if item.name=="Social Marketing":
                SelectedComponents.objects.filter(template=template,name="Social Marketing").delete()
                print(SelectedComponents.objects.filter(template=template,name="Social Marketing"))
                return viewEvent(request,currentEventId)

       
def removeLiveStream(request):
    """
	removeLiveStream Documentation
	Author: Mayada Al-Sawah C2-5
    This method enables the user to remove the LiveStream component after its been added to the event page.
    Args:
        No arguments taken.
    Returns:
			Redirected to a page saying that this component has been removed
    How to use the function:
			Open http://127.0.0.1:8000/viewEventAfterLaunch/ then click Remove Live Stream"
	""" 
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk=currentEventId)
 #   currentEvent = Event.objects.get(pk=81)
    template = currentEvent.template
    print currentEvent.template.eventName
    currentComponents = SelectedComponents.objects.filter(template=template)

    if request.method == "POST":
        for item in currentComponents:
            if item.name=="Live Stream":
                SelectedComponents.objects.filter(template=template,name="Live Stream").delete()
                print(SelectedComponents.objects.filter(template=template,name="Live Stream"))
                return viewEvent(request,currentEventId)


		
def createList(request):   
    """
	Author: Menna Khaled

	Story: C3-12

		This method allows the event creator to add a task list to the event page in order to be able to add tasks
	Args:
		This method takes no attributes.
		However, it is initiated through "POST" which takes from the user:
		title(text): title of the list
	Returns:
		The event page is refreshed displaying the created task list
	How to use the function:
		The event creator accesses the event page, adds title to the list and creates the list
		http://localhost:8000/TODO
	Exceptions:
		If the creator did not enter the title of the list, a message "This field is required" will be displayed
    """


    if request.method == 'POST':

        title = request.POST.get('listID', '')

        eventID = request.session["eventid"]

        event = Event.objects.get(pk = eventID)

        list = List.objects.get(event = event)

        list.title = title

        list.createdByUser = "yes"

        list.save()

        request.session['list'] = list

        return viewEvent(request , eventID )    
    
def addTask (request):
    """
	Author: Menna Khaled

	Story: C3-9

		This method allows the event creator to edit the task list related to a certain event by adding more items/tasks
	Args: 
		There are no attributes given to the method itself.
		However, it is initiated through "POST"  which takes from the user :
		description(text): title of the item/task
	Returns:
		The event page is refreshed displaying the updated task list with the new created items
	How to use the function:
		If there is a list created, the event creator will access the event page and clicks add Task else the user will have to create a task list then add task
		http://localhost:8000/AddTask
	Exception:
		If the creator did not enter the description of the task, a message "This field is required" will be displayed
    """

    
    eventID= request.session["eventid"]

    if request.method =='POST':

        title = request.POST.get('taskID' , '')

        if title:

            list = request.session['list']

            newTask = Item.objects.create(title = title , todoList = list, assignedTo = "")

            newTask.save()          
            
    return viewEvent(request , eventID)

def pendingEvent(request):
	"""
	Author: Fouad Hesham Said
	Story: C1-S5
		This method redirects to the page where the pending events for acceptance or rejection exists
	Args:
		There are no attributes given to the method
	Returns:
		This method redirects to the pending.html page
	"""
    flagPendingEvents = False
    allEvents = []
    events = Event.objects.filter(isApproved=False)
        
    for eventPending in events:
        if eventPending.isRejected==False:
            allEvents.append(eventPending)
            flagPendingEvents = True
            print "xxxxx"
    return render_to_response("Pending.html", locals())



def approve(request):
	"""
	Author: Fouad Hesham Said 
	Story: C1-S5
		This method approves the event found in the table in the pending.html page          
	Args:
		There are no attributes given to the method
		This method is initiated through "POST" that takes from the user:
		selects the event through the checkbox
	Returns:
		this method doesn't return an output, but it adds the event to the accepted events and refreshes the page
	"""
	if request.method =='POST':
		pendingList = request.POST.getlist('pending')
		if len(pendingList)==0:
			noEvents = "You have not selected any event"
			return pendingEvent(request)
		for pending in pendingList:
			event = Event.objects.get( id = pending )
			eventCreator = event.creator.email
			eventCreatorFirst = event.creator.first_name			
			eventCreatorLast = event.creator.last_name
			event.isApproved = True
			event.visibility = True
			send_mail('Notification', 'Dear ' + eventCreatorFirst + ' ' + eventCreatorLast + ' \n Your Event Has been approved.\n Thank you,\nEventati Team','eventati.noreply',[eventCreator] , False, 'eventati.noreply','Eventati2012')
			event.save()
		return showDashboard(request)

def reject(request):
	"""
	Author: Fouad Hesham Said
	Story:C1-S5
		This method rejects the event found in the table in the pending.html page          
	Args:
		There are no attributes given to the method
		This method is initiated through "POST" that takes from the user:
		selects the event through the checkbox
	Returns:
		this method doesn't return an output, but it adds the event to the rejected events and refreshes the page
	"""
	if request.method =='POST':
		pendingList = request.POST.getlist('pending')
		if len(pendingList)==0:
			noEvents = "You have not selected any event"
			return pendingEvent(request)
		for pending in pendingList:
			event = Event.objects.get( id = pending )			
			eventCreator = event.creator.email			
			eventCreatorFirst = event.creator.first_name			
			eventCreatorLast = event.creator.last_name
			event.isRejected = True	   
			event.save()		
			send_mail('Notification', 'Dear ' + eventCreatorFirst + ' ' + eventCreatorLast + ' \n Your Event Has been rejected.\n Thank you, \nEventati Team',
                      'eventati.noreply',[eventCreator] , False, 'eventati.noreply','Eventati2012')
		return showDashboard(request)
 
def systemModerator(request):

	return render_to_response("systemModerator.html")  

def deleteEvent(request):
	"""
	Author: Fouad Hesham Said
	Story: C1-S7
		This method deletes the event from the existing events by the Event Creator and sends a confirmation mail to the creator          
	Args:
		There are no attributes given to the method
		This method is initiated through "POST" that takes from the user:
		selects the event through the checkbox
	Returns:
		This method doesn't return an output, but it deletes the event from the database and sends an e-mail to the creator 
	"""
	eventID = request.session['eventid']
	tempEmail = request.session['email']
	for event in Event.objects.all():
		if(event.creator.email == tempEmail):
			Event.objects.get( id = eventID ).delete()
			send_mail('Notification', 'Dear User \n Your Event Has been deleted.\n Thank you, \n Eventati Team', 
			'eventati.noreply@gmail.com', [tempEmail], False, 'eventati.noreply','Eventati2012')
			return showDashboard(request)
	return showDashboard(request)

def bookmark(request):
    """
    Author: Fouad Hesham Said
    Story: C1-S15
        This method returns the public, created and invited events of a certain user in Bookmark.html          
    Args:
        This methood takes no arguments
    Returns:
        This method redirects to BookMark.html where it displays  the public, created and invited events of a certain user
    How to use the function:
        http://localhost:8000/bookmark
    """
    flagEventsExist = False
    userEmail = request.session['email']
    getUser = User.objects.get(email=userEmail)
    public = []
    publicEvents = Event.objects.filter(isPublic = True)
    for publicEvent in publicEvents:
        if publicEvent.creator!=userEmail:
            public.append(publicEvent)
            flagEventsExist = True
    createdEvents = Event.objects.filter(creator=getUser)
    createdPrivateEvents = []
    for privateEvent in createdEvents:
        if privateEvent.isPublic!=True:
            createdPrivateEvents.append(privateEvent) 
            flagEventsExist = True      
    invitedEvents=[]
    events=Invited.objects.filter(user=getUser)
    for event in events:
        if event.event.creator!=getUser:
            if event.event.isPublic!=True:
                 invitedEvents.append(event)
                 flagEventsExist = True
    return render_to_response("Bookmark.html", locals())
def listOfBookmarks(request):
	"""
	Author: Fouad Hesham Said
	Story: C1-S15
		This method returns all events chosen by the user to bookmark
	Args:
		This methood takes no arguments
	Returns:
		This method returns all events chosen by the user to bookmark
	How to use the function:
		http://localhost:8000/listOfBookmark
	"""
	userEmail=request.session['email']
	getUser = User.objects.get(email=userEmail)
	bookmarks = Bookmark.objects.filter(user=getUser)
	bookmarked=[]
	for bookmark in bookmarks:
		bookmarked.append(bookmark.event)
	print bookmark.event.template.eventName
	return render_to_response('DeleteBookmark.html', locals())

def deleteBookmark(request):
	"""
	Author: Fouad Hesham Said
	Story:C1-S15
		This method deletes the bookmarks chosen by the user
	Args:
		This methood takes no arguments
	Returns:
		This method redirects to the dashboard page after deleting the event
	How to use the function:
		http://localhost:8000/deleteBookmark
	"""
	if request.method=="POST":
		userEmail = emailSession['email']
		getUser = User.objects.get(email=userEmail)
		deletedBookmarked = request.POST.getlist('events')
		print deletedBookmarked
		if len(deletedBookmarked)==0:
			return listOfBookmarks(request)
		for bookmark in deletedBookmarked:
			eventBookmark = Event.objects.get(id=bookmark)
			Bookmark.objects.get(event=eventBookmark, user=getUser).delete()
		return showDashboard(request)              

def addBookmark(request):
    """
    Author: Fouad Hesham Said
    Story: C1-S15
        This method adds the bookmarks chosen by the user
    Args:
        This methood takes no arguments
    Returns:
        This method redirects to the dashboard home after adding the event
    Exception:
        If the user doesnt choose any events to bookmark the page is refreshed
    How to use the function:
        http://localhost:8000/addBookmarks
    """
    if request.method=="POST":
        userEmail = emailSession['email']
        getUser = User.objects.get(email=userEmail)
        favoriteEvents = request.POST.getlist('events')
        if len(favoriteEvents)==0:
            return bookmark(request)
        for id in favoriteEvents:
            eventBookmark = Event.objects.get(id=id)
        for bookmarked in Bookmark.objects.all():
            if bookmarked.user==getUser and bookmarked.event==eventBookmark:
                return bookmark(request)
        newBookmark = Bookmark.objects.create(user=getUser, event=eventBookmark)
        newBookmark.save()
        return showDashboard(request)
    
def viewAttend(request):
    """
    Author: Ahmed Y. Hashad C3-4
    def viewAttend(request):
    This method creates a list of all the attendees for a certain event
    Arg:
    There are no arguments
    Return:
    It returns a list of the attendees
    How it works:
    The user accesses the event page which will display the number of attendees.	
    """
    eventID = request.session["eventid"]
    event = Event.objects.get(pk = eventID)
    attend = Attending.objects.filter(event = event)
    attendSize = attend.count()
    return (attendSize)

def viewMaybe(request):
    """
    Author: Ahmed Y. Hashad C3-4
    def viewMaybe(request):
    This method creates a list of all the Maybe attendees for a certain event
    Arg:
    There are no arguments
    Return:
    It returns a list of the Maybe attendees
    How it works:
    The user accesses the event page which will display the number of the Maybe attendees.
    """
    eventID = request.session["eventid"]
    event = Event.objects.get(pk = eventID)
    maybe = MaybeAttending.objects.filter(event = event)
    maybeSize = maybe.count()
    return (maybeSize)

def viewNotAttending(request):
    """
    Author: Ahmed Y. Hashad C3-4
    def viewNotAttending(request):
    This method creates a list of all the non attendees for a certain event
    Arg:
    There are no arguments
    Return:
    It returns a list of the non attendees
    How it works:
    The user accesses the event page which will display the number of the non attendees.
    """
    eventID = request.session["eventid"]
    event = Event.objects.get(pk = eventID)
    notAttend = NotAttending.objects.filter(event = event)
    notAttendSize = notAttend.count()
    return (notAttendSize)

def viewPayedAttendees(request):
    """
    Author: Ahmed Y. Hashad C3-4
    def viewPayedAttendees(request):
    This method creates a list of all the payed attendees for a certain event
    Arg:
    There are no arguments
    Return:
    It returns a list of the payed attendees
    How it works:
    The user accesses the event page which will display the number of payed attendees.
    """
    eventID = request.session["eventid"]
    event = Event.objects.get(pk = eventID)
    pay = PayedAttendees.objects.filter(event = event)
    paySize = pay.count()
    return (paySize)

def viewAllAttending(request):
    """
    Author: Ahmed Y. Hashad C3-18
    def viewAllAttending(request):
    This method creates a list of all the attendees for a certain event
    Arg:
    There are no arguments
    Return:
    It returns a list of the attendees
    How it works:
    The user accesses the event page which will display the number of attendees.    
    """
    eventID = request.session["eventid"]
    event = Event.objects.get(pk = eventID)
    attend = Attending.objects.filter(event = event)
    for person in attend:
        person.user.first_name + " " + person.user.last_name
    return render_to_response ("allAttend.html", locals())

def viewAllMaybe(request):
    """
    Author: Ahmed Y. Hashad C3-18
    def viewAllMaybe(request):
    This method creates a list of all the Maybe attendees for a certain event
    Arg:
    There are no arguments
    Return:
    It returns a list of the Maybe attendees
    How it works:
    The user accesses the event page which will display the number of the Maybe attendees.
    """
    eventID = request.session["eventid"]
    event = Event.objects.get(pk = eventID)
    maybe = MaybeAttending.objects.filter(event = event)
    for person in maybe:
        person.user.first_name + " " + person.user.last_name
    return render_to_response ("allMaybe.html", locals())

def viewAllNotAttending(request):
    """
    Author: Ahmed Y. Hashad C3-18
    def viewAllNotAttending(request):
    This method creates a list of all the non attendees for a certain event
    Arg:
    There are no arguments
    Return:
    It returns a list of the non attendees
    How it works:
    The user accesses the event page which will display the number of the non attendees.
    """
    eventID = request.session["eventid"]
    event = Event.objects.get(pk = eventID)
    notAttend = NotAttending.objects.filter(event = event)
    for person in notAttend:
        person.user.first_name + " " + person.user.last_name
    return render_to_response ("allNotAttending.html", locals())


def viewAllPayed(request):
    """
	Author: Ahmed Y. Hashad C3-18
	def viewAllPayed(request):
	This method creates a list of all the payed attendees for a certain event
	Arg:
	There are no arguments
	Return:
	It returns a list of the payed attendees
	How it works:
	The user accesses the event page which will display the number of payed attendees.
	"""
    eventID = request.session["eventid"]
    event = Event.objects.get(pk = eventID)
    payed = PayedAttendees.objects.filter(event = event)
    for person in payed:
        person.user.first_name + " " + person.user.last_name
    return render_to_response ("allPayedAttendees.html", locals())


def goToEvent(request):
    if request.method == "POST":
        eventID = request.session['eventid']
        return viewEvent(request, eventID)    
    

def viewListProgress(list):
    
    """
        def viewListProgress(list):
        Author : Reem Tarek C3-15
        This method counts the number of completed items/tasks of a Task list related to a certain event.
        Args:
        list (List) : the task list of a certain event.
        Returns:
        The method returns  the number of completed items/tasks.
        How to use this function:
        When The event creator accesses the event page the method will be called to count the completed tasks.
    """
    items = Item.objects.filter(todoList = list )
    if items:
        completedTasks = Item.objects.filter(todoList = list , completed = True)
        noOfCompletedTasks  = int ((completedTasks.count() * 1.00 /items.count()) * 100 )
        return noOfCompletedTasks
    return 0


#def payForEvent(request):
#	"""
#	    Author: Hana Saoud
#	    Story: C4-8
#	    This method is used to gather the event number the user entered in the call to charge him with payment amount 
#	    Arg:
#	    The method takes no inputs and take a request from TwilioPay.xml
#	    Return:
#	    The method returns instructions to the caller to enter the number of the event 
#	    How it works:
#	    When the user calls this method is called 
#	"""
#	if request.method == "GET":
#		eventNumber = request.GET.get('name', '')
#        response = twilio.twiml.Response()
#	    response.gather()
#	    response.say("You have entered")
#	    return render_to_response('gather.xml')
#	return response
    
def measureAttendee(request,eventId):
    """
    Author: Dalia Hegazy C4-13
    This method is used to get the count of the users attending this event , may be attending and the not attending users so that
    the event creator can view the pie chart of it
    Arg:
    the methods takes the request that is sent when a page is requested  and takes the event id which represents the id of 
    certain event
    Return:
    it returns a page containd the pie chart of the attendees including the may be attending and not attending users
    How it works:
    the event creator clicks on the link which is view attendee chart 
    """
    if 'email' not in request.session:
        return HttpResponseRedirect('/homePage/')
    if request.session['email'] == "":
        return HttpResponseRedirect('/homePage/')
    
    user = User.objects.get(email=request.session['email'])
    event = Event.objects.get(pk = eventId)
    if user.id != event.creator.id:
        return HttpResponseRedirect("/homePage/")
    
    attendingUser = Attending.objects.filter(event=eventId).count()
    maybeAttendingUser =  MaybeAttending.objects.filter(event=eventId).count()
    notAttendingUser = NotAttending.objects.filter(event=eventId).count()
    errorMsg = ""
    if attendingUser==0 and maybeAttendingUser==0 and notAttendingUser==0:
        errorMsg = "not"
    return render_to_response("ChartAttendee.html", locals())

def measureLike(request,eventId):
    """
    Author: Dalia Hegazy C4-13
    This method is used to get number of likes for four different dates in order to draw the chart of likes
    Arg:
    the methods takes the request that is sent when a page is requested  and takes the event id which represents the id of 
    certain event
    Return:
    it returns a page that contains the chart of the users who liked the event
    How it works:

    the event creator clicks on the link which is view likes chart 
    """
    if 'email' not in request.session:
        return HttpResponseRedirect('/homePage/')
    if request.session['email'] == "":
        return HttpResponseRedirect('/homePage/')
    
    user = User.objects.get(email=request.session['email'])
    event = Event.objects.get(pk = eventId)
    if user.id != event.creator.id:
        return HttpResponseRedirect("/homePage/")
    
    likeEvent = LikeEvent.objects.filter(event=eventId).order_by('date')
    likeEventCount = likeEvent.count()
    
    if likeEventCount==0:
        errorMsg = "not"
        return render_to_response("ChartLike.html", locals())
    
    dateDifference = likeEvent[likeEventCount-1].date-likeEvent[0].date
    rangeDate = dateDifference/3
    date1=likeEvent[0].date
    date2 = likeEvent[0].date + rangeDate
    date3 = date2 + rangeDate
    date4=likeEvent[likeEventCount-1].date
    
    numberOfLikes1 = LikeEvent.objects.filter(event=eventId).filter(date__lte=date1).count()
    numberOfLikes2 = LikeEvent.objects.filter(event=eventId).filter(date__lte=date2).count()
    numberOfLikes3 = LikeEvent.objects.filter(event=eventId).filter(date__lte=date3).count()
    numberOfLikes4 = LikeEvent.objects.filter(event=eventId).filter(date__lte=date4).count()
    return render_to_response("ChartLike.html", locals())





def assignTask(request):
    
    """
        def assignTask(request):
        Author : Reem Tarek C3-14
        This method allows the event creator to assign items of the event task list to event moderators.
        Args:
        There are no attributes given for the method itself
        However this method is initiated through "POST" which takes from the user:
        list : A list of checked boxes indicating the items or tasks the event creator wants to assign
        Returns:
        It calls the method viewEvent(list) that displays the updated event information.
        How to use this function:
        The event creator  accesses the event page, then checks the items he/she wants to assign to event moderators and then clicks on assign button
    """
    eventid = request.session["eventid"]
    event = Event.objects.get(pk = eventid) 
    
    if request.method =='POST':
        flag = False
        itemsList = request.POST.getlist('task')
        moderator = request.POST.get('Moderators' , '')
        user = User.objects.get(email = moderator)
        list = request.session['list']
        for item in itemsList:
            item = Item.objects.get(pk = item , todoList = list )
            if ( not item.completed):
                if(not event.creator == user):
                    item.assignedTo = user.first_name + " " + user.last_name
                    print item.assignedTo
                    item.save()
                    flag = True
                else:
                    item.assignedTo = "-"
                    item.save()
        if flag:
            print "HEREEEEEE"
            send_mail('Notification', 'Dear ' + user.first_name +" " +  user.last_name + '\n You have been assigned to ' + str(len(itemsList)) + '  new tasks in the event ' + event.template.eventName+ ' \n Thank you. \nEventati Team',
                              'eventati.noreply@gmail.com', [user.email], False, 'eventati.noreply', 'Eventati2012')
    
    eventID = request.session["eventid"]            
    return viewEvent(request , eventID)

def viewModerator (request):
    """
    Author: Menna Khaled
    Story: C3-16
        This method redners to a page that has all the users 
    Args:
        there are no attributes given for the method 
    Returns:
        redirects to Moderators.html that has all the users 
    How the function works:
        The creator will click on the button assign moderator in the event page and then will
        be directed to the page that has all the users
        http://127.0.0.1:8000/moderator/
    """   
    user = User.objects.all()
    return render_to_response("Moderators.html", locals())
	

def assignModerator (request):
    """
	Author: Menna Khaled
	Story: C3-16
		This method views all the users and assigns moderators to the event
	Args:
		There are no attributes given for the method itself
		However this method is initiated through "POST"		
	Returns:
		Redirects to the creator event page.		
	How the function works:
		The creator will choose the users and then click on the button assign to call the method
		http://localhost:8000/moderator/   
    """   
    if request.method== "POST":
        users = User.objects.all()
        assigned = EventModerator.objects.all()
        moderators = []
        email = request.session['email']
        eventID = request.session['eventid']
        event = Event.objects.get(id = eventID)
        
        if event.creator.email==email: 
            assignedList = request.POST.getlist('assign')  
            if len(assignedList) ==0:
                assign = "Please choose a user to assign"
                return render_to_response("Moderators.html", locals())
            for moderator in assignedList:
                getUser = User.objects.get(email=moderator)
                print getUser.email
                for user in assigned:
                    if user.user==getUser and user.event==event:
                        alreadyAssigned = "Already Assigned"
                        return viewEvent(request, eventID)

                
            assignedModerator = EventModerator.objects.create(user=getUser, event=event)
            assignedModerator.save()
            successAssigned = "You have succefuly assigned a moderator to your event"
            return viewEvent(request, eventID)
    else:
        return HttpResponse("Failed")  

		
def viewAssignedTasks(list , userEmail):
    """
	Author: Menna Khaled

	Story: C3-16

		This method returns all the items assigned to the event moderator
	Args:
		This method takes the list and user email as attributes
	Returns:
		This method returns all the items assigned to the event moderator    
    
    """

    user = User.objects.get(email = userEmail)
    name = user.first_name +" " + user.last_name
    items = Item.objects.filter(todoList = list, assignedTo = name)
    return items
	
def addContactForm(request):
    """
    def addContactForm(request):
    Author : Sebbah Safey
    Story : C5-13
    this method takes the attributes of contactus and allows ther user to submit his contactform
    Args : 
       no arguments
    Returns: 
       it returns to the Dashboardhome page
    How to use the function:
       Type the localhost "localhost:8000/Contactus/" 
"""
    if request.method == "POST":
        message = request.POST.get('message','')
        email = request.POST.get('email','')
        if message:
            if email:
                newContact = Contact.objects.create(message = message, email = email)
                return render_to_response("DashboardHome.html", locals())
                
            else:
                Errormessage = "Please enter your message"
                return render_to_response("ContactUs.html", locals())
        else:
            Errormessage = "Please enter your email "
            return render_to_response("ContactUs.html", locals())
    else: 
        return render_to_response("ContactUs.html", RequestContext(request))

def viewEditBasicInformation(request):
        
    """
    Author: Hadeel Mohamed
    Story: C2-16
    viewEditBasicInformation documenation
    this method redirects the creator who wants to edit the basic components of his or her event to the edit basic components 
    page that retrieves from him the new start, end times and dates and then updates it in the event
    Args:
    It takes no input however it works by request when the creator clicks on edit basic information
    Returns:
    It redirects the creator to the edit basic information page
    How the function works:
    The method is called upon clicking on the edit basic information button in the event creator page
   
    """
    template=request.session['template']
    
    if request.method == "POST":
        eventName = request.POST.get('EventName')
        

        startTime= request.POST.get('StartTime')
        endTime= request.POST.get('EndTime') 
        
        template.eventName = eventName
        startDay=request.POST.get('startDay')
        endDay=request.POST.get('endDay')
    return render_to_response("EditBasic.html", locals())
def editBasicInformation(request):
    """
    Author: Hadeel Mohamed
    Story: C2-16
    editBasicInformation documenation:
    The method edits the basic components of the event from the event page after the event was launched
    it retrieves from the edit editBasic html page the new URLs
    the method replaces the old URLs and redirect the creator back to the creator event page
    Args:
    This method takes no inputs however it uses the POST method which retrieves from the user the new URLs
    Returns:
    There is no output however it returns the user back to the creator event page with the edited basic 
    components
    How the function works:
    The method is called upon clicking on the submit button after editing the basic information wanted    
    """
     
    currentEventId=request.session["eventid"]
    currentEvent = Event.objects.get(pk = currentEventId)
    template=currentEvent.template
    print("iiiiii")
    print(template.id)
    
    
    if request.method == "POST":
            eventName = request.POST.get('EventName')
            print("hhhhhhhhh")
            print(eventName)
            startTime= request.POST.get('StartTime')
            endTime= request.POST.get('EndTime') 
            template.eventName = eventName
            
            
            startDay=request.POST.get('startDay')
            print(startDay)
            endDay=request.POST.get('endDay')
            print(endDay)
            
            if template.name == "Wedding" :
                brideName=request.POST.get('BrideName')     
                groomName=request.POST.get('GroomName')
                template.brideName = brideName 
                template.groomName = groomName
                template.save()
            if template.name == "Engagement" :
                brideName=request.POST.get('BrideName')
                groomName=request.POST.get('GroomName')
                template.brideName = brideName 
                template.groomName = groomName 
                template.save()
            if template.name == "Birthday" :
                birthdayOwner=request.POST.get('BirthdayOwner')
                template.birthdayOwner = birthdayOwner
                template.save()
            if template.name == "Concert" :
                singerName=request.POST.get('SingerName')
                template.singerName = singerName
                template.save()
            if template.name == "Charity" :
                charityType=request.POST.get('CharityType')
                template.charityType = charityType
                template.save()
        #    if template.name == "Create your own template" :
         #       Description = request.POST.get('Description')
          #      if (Description == "null"):
           #             Description="not decided"
            #    else:    
            #            template.description = Description
             #           template.save()
        
        
            template.startDate = startDay
            template.endDate = endDay
            template.save()  
            print("innnnn")
            template.startTime = startTime
            template.endTime = endTime
            template.save()
                         
    return viewEvent(request,currentEventId)

def editRefreshAgenda (request):
    """    
    def editRefreshAgenda(request):
    Author: Sarah Hesham
    Story:c3-7
    This method is called as the user edits activities so as to update the table and display the latest updates of the agenda.
    Args:
        There are no attributes for the method  
    Returns:
        redirects the user to the updated EditAgenda.html where the user views updated agenda
    How to use the function:
        This method is called and used as the user starts adding new activities so as to update the agenda.
    """
    creation = "True"
    agenda =  request.session['agenda'] 
    Activities = Activity.objects.filter(agendaID = agenda)
    template = request.session["template"]

    return render_to_response("EditAgenda.html" , locals())

def editEventActivity(request):
    """
        def editActivity(request)
        Author : Sarah Hesham 
        Story :C3-7
        This method allows the event creator to edit activities of the event's agenda.
        Args:
            There are no attributes given for the method itself
            However this method is initiated through "POST" which takes from the user:
                selectedActivity : A list of checked boxes indicating the activities the event creator wants to edit
                Description (text) : title of the activity
                Start Time (timeField) : activity start time
                End Time (timeField) : activity end time
        Returns:
            It calls the method editRefreshAgenda(request) that displays the updated Agenda.
        How to use this function:
            The event creator will access eventpage and then press the button "Edit Agenda" and then edit the activity by pressing the button"Edit"
    """  
    creation="True"
    template = request.session["template"]
    agenda =  request.session['agenda']   
    Activities = Activity.objects.filter(agendaID = agenda)
    if request.method =='POST':
        selectedActivity = request.POST.get('activity')
        text = request.POST.get('textID' , '')
        start = request.POST.get('StartTime' , '')
        end = request.POST.get('EndTime' , '')
        agenda = request.session['agenda']
        newActivity = Activity.objects.get(pk =selectedActivity, agendaID = agenda)
        #if start >= template.startTime and end<=template.endTime:
        newActivity.description = text
        newActivity.startTime = start
        newActivity.endTime = end
        newActivity.save()
        return  editRefreshAgenda(request)
        #else:
         #   wrongEditTime = "True"
         #   return render_to_response("EditAgenda.html" , locals())      
        
def addEventActivity(request):
    """
        def addEventActivity(request)
        Author : Sarah Hesham 
        Story :C3-7
        This method allows the event creator to add new activities to the event's agenda.
        Args:
            There are no attributes given for the method itself
            However this method is initiated through "POST" which takes from the user:
                Description (text) : title of the activity
                Start Time (timeField) : activity start time
                End Time (timeField) : activity end time        
        Returns:
            It calls the method editRefreshAgenda(request) that displays the updated Agenda.
        How to use this function:
            The event creator will access eventpage and then press the button "Edit Agenda" and then add the activity "Add Activity"
    """   
    creation = "True"
    agenda =  request.session['agenda'] 
    template = request.session["template"]
    Activities = Activity.objects.filter(agendaID = agenda)
    if request.method=='POST':
        text = request.POST.get('textID' , '')
        start = request.POST.get('StartTime' , '')
        end = request.POST.get('EndTime' , '')
        template = request.session["template"]
        agendaSession = request.session['agenda']
        print start
        print end 
        print template.startTime     
        #if start >= template.startTime and end<=template.endTime:

        newActivity = Activity()
        newActivity.description = text
        newActivity.startTime = start            
        newActivity.endTime = end
        newActivity.agendaID = agendaSession
        newActivity.save()
        return  editRefreshAgenda(request)
        #else:
                #wrongTime = "True"
                #return render_to_response("EditAgenda.html" , locals())

         
          
def deleteEventActivity(request):
    """
        def deleteEventActivity(request)
        Author : Sarah Hesham 
        Story :C3-7
        This method allows the event creator to delete activities from the event's agenda.
        Args:
            There are no attributes given for the method itself
            However this method is initiated through "POST" which takes from the user:
                selectedActivity : A list of checked boxes indicating the activities the event creator wants to delete
        Returns:
            It calls the method editRefreshAgenda(request) that displays the updated Agenda.
        How to use this function:
            The event creator will access eventpage and then press the button "Edit Agenda" and select the activity he wishes to delete and press "Delete"
    """
    if request.method =='POST':
        selectedActivity = request.POST.get('delete')
        agenda = request.session['agenda']
        Activity.objects.filter(pk = selectedActivity , agendaID = agenda).delete()
    return editRefreshAgenda(request)
   
        
    